[android] 09_数据库事务

Android 4.0

数据库事务


 
使用SQLiteDatabasebeginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTransaction()之前调用了setTransactionSuccessful() 方法设置事务的标志为成功则提交事务,如果没有调用setTransactionSuccessful() 方法则回滚事务。使用例子如下:
 SQLiteDatabase db = ....;
db.beginTransaction();//开始事务
try {
    db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4});
    db.execSQL("update person set name=? where personid=?", new Object[]{"传智", 1});
    db.setTransactionSuccessful();//调用此方法会在执行到endTransaction() 时提交当前事务,如果不调用此方法会回滚事务
} finally {
    db.endTransaction();//由事务的标志决定是提交事务,还是回滚事务
}
db.close();
上面两条SQL语句在同一个事务中执行。

Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.

Here is the standard idiom for transactions:

   db.beginTransaction();
   try {
     ...
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
 

public class TestTransaction extends AndroidTestCase {
 
    String s;
    public void test() throws Exception {
        PersonDBOpenHelper helper = new PersonDBOpenHelper(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        db.beginTransaction();// 开始数据库的事务
        try {
            db.execSQL("update person set account = account-100 where name='zhangsan'");
            // s.equals("haha");
            db.execSQL("update person set account = account+100 where name='zhangsan0'");
            db.setTransactionSuccessful(); // 如果没有标记数据库事务成功 //数据会回滚
        } finally {
            db.endTransaction(); // 检查是否设置了事务成功的flag
            db.close();
        }
    }
}