Home » Android » Do efficient SQLite Inserts with Android

Do efficient SQLite Inserts with Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’ve got an activity that handles the printers of my University. The Printers can be downloaded over the internet and are then stored in a SQLite database. The problem is, that there are about 500 database entries that have to be made to store them, which is with my code very time intensive (approx. 30s on a Google Nexus S). My code to do so is this:

printerDB = new PrinterListOpenHelper(this);
SQLiteDatabase db = printerDB.getWritableDatabase();
db.execSQL("INSERT INTO destination (id, destination) VALUES(1,'BSAC240');");
db.execSQL("INSERT INTO destination (id, destination) VALUES(2,'BSAD152');");
...

This is followed by approx. 500 similar rows. I also tried to do it with a single

db.rawQuerry("INSERT INTO destination (id, destination) VALUES(1,'BSAC240');
INSERT INTO destination (id, destination) VALUES(2,'BSAD152');.......");

but then only the first INSERT statement is actually executed.

Does anybody know a trick for making this efficient? Or are the Android Databases actually that slow?

Thanks a lot for your help!
Simon

How to&Answers:

Does it work any better if you put them into a transaction?

BEGIN TRANSACTION
  INSERT INTO destination (id, destination) VALUES(1,'BSAC240');
  INSERT INTO destination (id, destination) VALUES(2,'BSAD152');
END TRANSACTION

Or even (updated following comments)

db.beginTransaction()
try {
    db.execSQL("INSERT INTO destination (id, destination) VALUES(1,'BSAC240');");
    db.execSQL("INSERT INTO destination (id, destination) VALUES(2,'BSAD152');");
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}