Android的sqlite的回滚 [英] Android sqlite rollback

查看:200
本文介绍了Android的sqlite的回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做数据库SYN。下载SQL Server和sqlite.If有一些情况之间的数据同时更新/ SQLite中插入记录,互联网连接速度较慢或跌落则需要推出back.Is有可能在这个code或如何在这里使用的事务。

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);
}

请帮我。

在此先感谢...

推荐答案

下面是SQLite中使用事务的一个简短的例子(DB是一个SQLiteDatabase实例如下):

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();
}

通知,其重要的是你选择的任何方法,抛出和异常,以取代//你的SQL的东西。使用insertOrThrow(),或者如果你需要更多的灵活性SQLiteStatement实例(其.execute方法总是抛出异常的错误)。

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).

注意,你并不需要explicititly回滚。如果调用db.endTransaction()不.setTransactionSuccessful(),它会自动回滚。

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

只要记住总是把setTransactionSuccessful你最后的SQLException投掷方法后:)

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

您可以轻松与另一个catch块扩展此,搭上网​​络超时异常。

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

这篇关于Android的sqlite的回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆