小编Kar*_*pan的帖子

Android数据库事务

我创建了一个数据库.我想做交易.SaveCustomer()包含多个语句,以便Customer, CustomerControl, Profile, Payment在那时将记录插入表中.

当用户调用 SaveCustomer()方法时,该数据将转到这4个表.所以我该如何进行交易?如果一个表插入失败,则需要回滚所有内容.例如,当第3个表插入记录时出现错误,那么还需要回滚前两个表的插入记录.

看我的代码:

public void saveCustomer(){
    DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(RetailerOrderKeyActivity.this);
    dbAdapter.openDataBase();
    ContentValues initialValues = new ContentValues();
    initialValues.put("CustomerName",customer.getName());
    initialValues.put("Address",customer.getAddress());
    initialValues.put("CustomerPID",strPID);
    initialValues.put("Date",strDateOnly);
    long n = dbAdapter.insertRecordsInDB("Customer", null, initialValues);

}
Run Code Online (Sandbox Code Playgroud)

同样其他声明也在那里.

DBAdpter代码是:

public long insertRecordsInDB(String tableName, String nullColumnHack,ContentValues initialValues) {
    long n =-1;
    try {
        myDataBase.beginTransaction();
        n = myDataBase.insert(tableName, nullColumnHack, initialValues);

        myDataBase.endTransaction();
        myDataBase.setTransactionSuccessful();
    } catch (Exception e) {
        // how to do the rollback 
        e.printStackTrace();
    }

    return n;
}
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

public class DBAdapter extends …
Run Code Online (Sandbox Code Playgroud)

sqlite android transactions

82
推荐指数
3
解决办法
9万
查看次数

标签 统计

android ×1

sqlite ×1

transactions ×1