Friday 20 May 2016

Faster sqlite database insertion

Many a time we have the requirement to insert bulk of data into Android SQLite database, but the normal database insert() operation provided by SQLiteDatabase.java class will take more time in such situation.
So today we will see how to make database insertion faster for bulk data insertion by using transaction with database insert() operation.
Let's see a sqlite database operation example
Here I will take an example of managing student database with just insert operation


Student.java
public class Student {

   private int id;
   private String name;

   public long getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return this.name;
   }

   public void setName(String name) {
      this.name = name;
   }

   @Override   public String toString() {
      return name;
   }
}






DataBaseWrapper.java


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseWrapper extends SQLiteOpenHelper {

   public static final String STUDENTS = "Students";
   public static final String STUDENT_ID = "_id";
   public static final String STUDENT_NAME = "_name";

   private static final String DATABASE_NAME = "Students.db";
   private static final int DATABASE_VERSION = 1;

  // creation SQLite statement
private static final String DATABASE_CREATE = "create table " + STUDENTS + "(" + STUDENT_ID + "" +
      " integer primary key autoincrement, " + STUDENT_NAME + " text not null);";

public DataBaseWrapper(Context context) {
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Overridepublic void onCreate(SQLiteDatabase db) {
   db.execSQL(DATABASE_CREATE);
}
@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   db.execSQL("DROP TABLE IF EXISTS " + STUDENTS);
   onCreate(db);
}
}
StudentOperations.java
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class StudentOperations {

   // Database fields   private DataBaseWrapper dbHelper;
   private String[] STUDENT_TABLE_COLUMNS = { DataBaseWrapper.STUDENT_ID,
 DataBaseWrapper.STUDENT_NAME };
   private SQLiteDatabase database;

   public StudentOperations(Context context) {
      dbHelper = new DataBaseWrapper(context);
   }

   public void open() throws SQLException {
      database = dbHelper.getWritableDatabase();
   }

//normal database insert operation
   public void addStudent(String name) {

      for(int i=0; i<1000;i++) {
         ContentValues values = new ContentValues();
         values.put(DataBaseWrapper.STUDENT_NAME, name);
         long studId = database.insert(DataBaseWrapper.STUDENTS, null, values);
      }
   }

//faster database insert operation
public void addStudentbulk(String name) { database.beginTransaction(); for(int i=0; i<1000;i++) { ContentValues values = new ContentValues(); values.put(DataBaseWrapper.STUDENT_NAME, name); database.insert(DataBaseWrapper.STUDENTS, null, values); } database.setTransactionSuccessful(); database.endTransaction(); } }
MainActivity.java 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private StudentOperations studentDBoperation;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        studentDBoperation = new StudentOperations(this);
        studentDBoperation.open();
        long startTime = System.nanoTime();
        //studentDBoperation.addStudent("Chetan");        
        studentDBoperation.addStudentbulk("Chetan");
        long endTime = System.nanoTime();
        long duration = (endTime - startTime)/1000000000;
        System.out.println("time taken : "+duration);
    }

}
You can calculate the time taken by both the operation I have also 
include the logic of time calculation to perform each operation.
You can comment the either operation and can get result
For me
Time take to insert 1000 students record is
by normal database operation operation : 
6+ seconds
by faster database operation operation :
less than one seconds
Try it yourself
Please suggest if any update.
Updates are always welcome
HAPPY CODING :)


source code  https://github.com/gaikwadChetan93/FasterDatabaseOperation

My Apps MobileUtility


1 comment: