交易機制 Transaction

1 篇文章 / 0 new
author
交易機制 Transaction

db.beginTransaction();
try {
    ...
    db.setTransactionSuccessful();
    //在setTransactionSuccessful和endTransaction之間不進行任何數據庫操作
} catch(Exception e){
    //當數據庫操作出現錯誤時,需要捕獲異常,結束交易
    db.endTransaction();
    throw e;
} finally {
    db.endTransaction();
    //當call endTransaction() 時未呼叫過 setTransactionSuccessful() 則系統自動進行 rollback 動作
}

範例:

public class DatabaseOpenHelper extends SQLiteOpenHelper {
    private static final String DB_NAME="MEMBER"; //database name
    public static final String TABLE_NAME="member";
    //欄位名稱
    public static final String COLUMN_ID="_id";
    public static final String COLUMN_NAME="name";
    public static final String COLUMN_POSITION="position";
    public static final String COLUMN_NUMBER="number";
    //初始資料
    private String[][] datas = newString[][] { {"張一","捕手","4"},{"李二","三壘手","5"},{"王三","投手","7"},{"吳四","二壘手","14"},{"陳五","外野手","9"} };
   
    public DatabaseOpenHelper(Context context) {
        //指定databsae名稱,若不存在則 call onCreate(),若資料庫已存在則 call onUpgrade()
        super(context,DB_NAME,null,1);
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try{
            //table建立
            StringBuilder createSql = new StringBuilder();
            createSql.append("createtable"+Database.TABLE_NAME+"(");
            createSql.append(Database.COLUMN_ID+"integerprimarykey,");
            createSql.append(Database.COLUMN_NAME+"text,");
            createSql.append(Database.COLUMN_POSITION+"text,");
            createSql.append(Database.COLUMN_NUMBER+"text");
            createSql.append(")");
            db.execSQL(createSql.toString());
            db.setTransactionSuccessful();
        }finally{
            db.endTransaction();
        }
        //填入資料
        db.beginTransaction();
        try{
            for(String[] data:datas) {
                ContentValues values = new ContentValues();
                values.put(Database.COLUMN_NAME,data[0]);
                values.put(Database.COLUMN_POSITION,data[1]);
                values.put(Database.COLUMN_NUMBER,data[2]);
                db.insert(Database.TABLE_NAME,null,values);
            }
            db.setTransactionSuccessful();
        }finally{
            db.endTransaction();
        }
    }
    //database 更新
    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) { }
}

Free Web Hosting