使用SQLiteDatabase的beginTransaction()方法能夠開啓一個事務,程序執行到endTransaction() 方法時會檢查事務的標誌是否爲成功,若是程序執行到endTransaction()以前調用了setTransactionSuccessful() 方法設置事務的標誌爲成功則提交事務,若是沒有調用setTransactionSuccessful() 方法則回滾事務。sql
下面是一個例子:spa
/**事務
* 保存連載更新的最大章節數get
*it
* @param bookIdio
* @param bookChapterTotalNumtable
*/程序
public void saveBookChapterTotalNum(String bookId, int bookChapterTotalNum) {方法
synchronized (MyOpenHelper.databaseLock) {db
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);
}
}
}