Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android sqlite rollback

Tags:

android

sqlite

I am doing database syn. Downloading data between sql server and sqlite.If there some circumstance while updating/inserting records in sqlite ,internet connectivity is slow or drop then need to roll back.Is it possible in this code or How to use Transaction here.

 public void insertTableRecords(String strTableName, String[] strToFields, String[] strValues){
    DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
    dbAdapter.openDataBase();
    ContentValues initialValues = new ContentValues();
    for(int i=0 ;i<strToFields.length;i++){
        initialValues.put(strToFields[i],strValues[i]);
    }
    long n = dbAdapter.insertRecordsInDB(strTableName, null, initialValues);
    System.out.println( " -- inserted status : --- " + n);
}

Please help me.

Thanks in advance...

like image 565
Piraba Avatar asked Aug 02 '11 08:08

Piraba


1 Answers

Here's a short example of using transactions in SQLite (db is a SQLiteDatabase instance in the following):

try {
    db.beginTransaction();
    // your sql stuff
    db.setTransactionSuccessful();
} catch(SQLException e) {
    // do some error handling
} finally {
   db.endTransaction();
}

Notice, its important that whatever method you choose to replace "//your sql stuff" with throws and exception. Use insertOrThrow() or if you need more flexibility SQLiteStatement instances (their .execute methods always throws exceptions on error).

Notice, you do not need to explicititly rollback. If you call db.endTransaction() without .setTransactionSuccessful() it will roll back automatically.

Just remember always to put setTransactionSuccessful after your last SQLException throwing methods :)

You could easy extend this with another catch block, to catch exceptions for network time outs.

like image 190
JustDanyul Avatar answered Sep 19 '22 23:09

JustDanyul