A transaction (Transaction) is the basic unit of concurrency control. The so-called transaction, which is a sequence of operations that are either executed or not executed, is an inseparable unit of work.
A simple example, such as a bank transfer job: a debit from one account and an additional account, both of which are either executed or not executed. Can not say that if the execution of an account after the deduction, a sudden power outage, another account has not been increased operation.
In a situation like this, we should all consider them as a matter of affairs. Transactions are the units in which the database maintains data consistency, and data consistency is maintained at the end of each transaction.
Transactions should follow the acid characteristics, namely:
- Atomic (atomicity): The operations contained in a transaction are considered to be a logical unit in which the operations of the logical unit either succeed or fail altogether.
- Consistency (consistency): only legitimate data can be written to the database, or the transaction should roll it back to its original state.
- Isolation (Isolation): Transactions allow multiple users to concurrently access the same data without destroying the correctness and integrity of the data. At the same time, the modification of parallel transactions must be independent of the modifications of other parallel transactions.
- Durability (persistent): After the transaction ends, the result of the transaction must be cured.
In SQLite we use the following three paragraphs to handle transactions:
- Db.begintransaction ()
- Settransactionsuccessful ()
- Db.endtransaction ()
The reference code is as follows (Lisi the example of a $1000 to Zhangsan)
?
12345678910111213141516171819 |
String str;
public
void testTransaction()
throws Exception {
PersonSQLiteOpenHelper helper =
new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = helper.getWritableDatabase();
//开始数据库的事务
db.beginTransaction();
try
{
db.execSQL(
"update person set account=account-1000 where name=?"
,
new
Object[] {
"zhangsan"
});
str.equals(
"123"
);
db.execSQL(
"update person set account=account+1000 where name=?"
,
new
Object[] {
"lisi"
});
//设置数据库事务执行成功的flag
db.setTransactionSuccessful();
}
finally {
//如果执行成功(flag被设置,则commit(),否则rollback回滚
db.endTransaction();
}
}
|
The Str.equals ("123″") in which the statement appears with a null pointer error. This can be used to simulate a program exception interruption, and to view the results we find that the SQL statement does not perform only part of the case.
Moving from my blog, Xge technology blog:
Http://www.xgezhang.com/android_sqlite_transaction.html
Android Learning Note (8)--sqlite database transaction issues