Bulk Insertion on Android device

后端 未结 5 810
刺人心
刺人心 2020-11-28 02:40

I want to bulk insert about 700 records into the Android database on my next upgrade. What\'s the most efficient way to do this? From various posts, I know that if I use <

5条回答
  •  -上瘾入骨i
    2020-11-28 02:50

    Normally, each time db.insert() is used, SQLite creates a transaction (and resulting journal file in the filesystem), which slows things down.

    If you use db.beginTransaction() and db.endTransaction() SQLite creates only a single journal file on the filesystem and then commits all the inserts at the same time, dramatically speeding things up.

    Here is some pseudo code from: Batch insert to SQLite database on Android

    try
    {
      db.beginTransaction();
    
      for each record in the list
      {
        do_some_processing();
    
        if (line represent a valid entry)
        {
          db.insert(SOME_TABLE, null, SOME_VALUE);
        }
    
        some_other_processing();
      }
    
      db.setTransactionSuccessful();
    }
    catch (SQLException e) {}
    finally
    {
      db.endTransaction();
    }
    

    If you wish to abort a transaction due to an unexpected error or something, simply db.endTransaction() without first setting the transaction as successful (db.setTransactionSuccessful()).

    Another useful method is to use db.inTransaction() (returns true or false) to determine if you are currently in the middle of a transaction.

    Documentation here

提交回复
热议问题