執行事務
事務可用於以原子方式對資料庫進行多次更改。任何正常的交易遵循以下模式:
// 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()
無效。