1

When the first time i am running the app, i want to create a table and enter some rows into the table. For doing this, i wrote this bit of code and it is working fine:

            //Creating the table
        db.execSQL(MRM_BOOKING_LOGIN_TABLE_CREATE);         
        //Setting the values in the table
        ContentValues contentValuesLogin = new ContentValues();
        contentValuesLogin.put(USER_ID, "asdf");
        contentValuesLogin.put(PASSWORD, "1234");
        //Inserting a row in the table
        db.insert(MRM_BOOKING_LOGIN_TABLE, null, contentValuesLogin);

But i want to enter at least 15 to 20 rows in the table. Is it a good idea that every time after inserting one row, i will clear the ContentValues object (or create another object of ContentValues) and enter another row in the newly created table? In this way, the lines of code will increase a lot as well. I am sure there might be some other better alternative way to do the same. Please suggest

Regards,

user182944
  • 7,897
  • 33
  • 108
  • 174
  • Am I to assume that your 15-20 rows have hard-coded values (the user id and password is known ahead of time) or are they generated by some other means? If they are hard-coded, you can use resource string arrays and loops over them. – Jason Robinson Apr 15 '12 at 02:53

3 Answers3

2

I think, the only way to insert multiple records via db.insert is to use a loop. Combine it together with SQLite Transaction and it will speed up the process.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • then use **DatabaseUtils.InsertHelper**. read this http://www.outofwhatbox.com/blog/2010/12/android-using-databaseutils-inserthelper-for-faster-insertions-into-sqlite-database/ – waqaslam Apr 15 '12 at 03:18
2

A sample code:

try {
            // open the database
            db.beginTransaction();

            for (your objects) {
                ContentValues cv = new ContentValues();
                cv.put(COL1, obj.p1);
                cv.put(COL2, obj.p2);
                //.....

                long id = db.insertOrThrow(DATABASE_TABLE, COL_Id, cv);
            }

            db.setTransactionSuccessful();
} catch (Exception e) {
            throw e;
        } finally {
            db.endTransaction();
            // close database
        }
Bob
  • 22,810
  • 38
  • 143
  • 225
-1

You can insert multiple rows using ContentResolver.bulkInsert (Uri url, ContentValues[] values).

More information can be had from here:

Insertion of thousands of contact entries using applyBatch is slow

Hope this will help you.

Community
  • 1
  • 1
UVM
  • 9,776
  • 6
  • 41
  • 66