使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTransaction()之前调用了setTransactionSuccessful() 方法设置事务的标志为成功则提交事务,如果没有调用setTransactionSuccessful() 方法则回滚事务。
下面是一个例子:
/**
* 保存连载更新的最大章节数
*
* @param bookId
* @param bookChapterTotalNum
*/
public void saveBookChapterTotalNum(String bookId, int bookChapterTotalNum) {
synchronized (MyOpenHelper.databaseLock) {
SQLiteDatabase db = null;
try {
UserInfo userInfo = UserManager.INSTANCE.getUserInfo();
String username = userInfo.getUsername();
if (username == null || "".equals(username)) {
username = MyOpenHelper.AdminUser;
}
db = MyOpenHelper.getInstance().getWritableDatabase();
db.beginTransaction();
try {
if (isHave(db, bookId, username)) {
String sql = "UPDATE "
+ tableName
+ " SET bookChapterTotalNum=? WHERE bookId=? and (username=? or username='"
+ MyOpenHelper.AdminUser + "')";
Object[] bindArgs = { bookChapterTotalNum, bookId,
username };
db.execSQL(sql, bindArgs);
}
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeDB(db);
}
}
}