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.endTranscation();
}

private void insertOneHundredRecords() {
          for (int i = 0; i<100; i++) {
                     ContentValues values = new ContentValues();
                     values.put("FirstNumber", i);
                     values.put("SecondNumber", i);
                     values.put("Result", i*i);
                     sampleDB.insert(SAMPLE_TABLE_NAME,null,values);
           }
}

private void bulkInsertOneHundredRecords() {
          String sql = "INSERT INTO "+ SAMPLE_TABLE_NAME +" VALUES (?,?,?);";
          SQLiteStatement statement = sampleDB.compileStatement(sql);
          sampleDB.beginTransaction();
          for (int i = 0; i<100; i++) {
                    statement.clearBindings();
                    statement.bindLong(1, i);
                    statement.bindLong(2, i);
                    statement.bindLong(3, i*i);
                    statement.execute();
           }
           sampleDB.setTransactionSuccessful();	
           sampleDB.endTransaction();
}
Advertisements

One thought on “Batch insert to SQLite database on Android

  1. piano removal tucker April 13, 2014 at 3:07 am Reply

    I wanted to thank you for this wonderful read!! I certainly enjoyed every bit of
    it. I have you saved as a favorite to check out new stuff you post…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: