Tags

, , ,

Database operations are slow and in a situation where thousands of records have to be inserted, inserting each record consumes a lot of time and affects the performance of the application. In such situations,batch insert saves some overhead. A significant amount of time can be saved if batch inserts are made in a single transaction.

SQLite provides three simple methods in SQLiteDatabase class :
beginTransaction();
setTransactionSuccessful();
endTransaction();

These methods can be used to make all the insert calls in the same batch in a single transaction. Transactions are used when there is a need to perform a series of queries that either all complete or all fail. When a SQLite transaction fails an exception will be thrown. Start a transaction by calling the beginTransaction() method. Perform the database operations and then call the setTransactionSuccessful() to commit the transaction. Once the transaction is complete call the endTransaction() function.

A sample example code is shown below:

// Begin the transaction
db.beginTransaction();
try{
for each record in the list{
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_NAME,record);
db.insert(TABLE_NAME,null,contentValues);

}
// Transaction is successful and all the records have been inserted
db.setTransactionSuccessful();
}catch(Exception e){
Log.e(“Error in transaction”,e.toString());
}finally{
//End the transaction
db.endTransaction();
}