执行事务
事务可用于以原子方式对数据库进行多次更改。任何正常的交易遵循以下模式:
// You need a writable database to perform transactions
final SQLiteDatabase database = openHelper.getWritableDatabase();
// This call starts a transaction
database.beginTransaction();
// Using try/finally is essential to reliably end transactions even
// if exceptions or other problems occur.
try {
// Here you can make modifications to the database
database.insert(TABLE_CARS, null, productValues);
database.update(TABLE_BUILDINGS, buildingValues, COLUMN_ID + " = ?", new String[] { String.valueOf(buildingId) });
// This call marks a transaction as successful.
// This causes the changes to be written to the database once the transaction ends.
database.setTransactionSuccessful();
} finally {
// This call ends a transaction.
// If setTransactionSuccessful() has not been called then all changes
// will be rolled back and the database will not be modified.
database.endTransaction();
}
在活动事务中调用 beginTransaction()
无效。