黑馬學習---------------數據庫事務

使用SQLiteDatabase的beginTransaction()方法可以開啓一個事務,

   程序執行到endTransaction() 方法時會檢查事務的標誌是否爲成功,

   如果程序執行到endTransaction()之前調用了setTransactionSuccessful()方法設置事務的標誌爲成功則提交事務,

   如果沒有調用setTransactionSuccessful() 方法則回滾事務。

    /**
     * 轉賬
     */
    public void payment(Integer subtractId, Integer addId) {
       db = dbOpenHandler.getWritableDatabase();
       String sqlAdd = "update person set amount = amount + 10 where personid=?";
       String sqlSubtract = "update person set amount = amount - 10 where personid=?";
       db.beginTransaction();  // 開啓事務
       try{
           db.execSQL(sqlSubtract, new Object[]{subtractId});
           db.execSQL(sqlAdd, new Object[]{addId});
           db.setTransactionSuccessful(); // 在事務結束之前,設置事務標誌爲成功。必須手動設置。
       } finally{
           db.endTransaction(); // 結束事務, 若事務標誌爲成功,則提交事務。否則回滾事務。
       }
    }


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章