Android sqlite rollback
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.ou开发者_如何学编程t.println( " -- inserted status : --- " + n);
}
Please help me.
Thanks in advance...
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.
This insertion is effecting only one table.So by checking variable n you can find whether data is inserted or not.There is nothing in between it.No need any Transaction here.
If you mean by rollback, deleting the added rows; this is rather easy ... You could add a TIMESTAMP to each added row and set its value to System.currentTimeMillis()
... Save the first System.currentTimeMillis()
and if you want to rollback you can DELETE
from the table all the rows added after the timestamp saved in your program
It seems you are only updating the table after you have one complete row... Here is a code that will help you determine if the phone is still connected to the network, and accordingly, you can continue retreival of the rows or not.
manifest
Check if connected and continue
ConnectivityManager conManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
if(networkInfo.isConnected()){
//YOUR CODE
}
精彩评论