Android study notes (8) -- transactions in the Sqlite database, androidsqlite
Transaction is the basic unit of concurrency control. A transaction is a sequence of operations. These operations are either executed or not executed. It is an inseparable unit of work.
In a simple example, for example, bank transfers: either the two operations are executed or not executed to deduct money from one account and add money to the other account. It cannot be said that after the deduction of an account is completed, the system suddenly loses power and the other account does not perform the addition operation.
In such a case, we should regard them as a transaction. Transactions are the units in which the database maintains data consistency and maintain data consistency at the end of each transaction.
Transactions should follow the ACID feature, namely:
- Atomic (Atomicity): operations contained in a transaction are considered as a logical unit. Operations in this logical unit are either all successful or all failed.
- Consistency (Consistency): only valid data can be written to the database, otherwise the transaction should roll back to the initial state.
- Isolation: Transactions allow multiple users to concurrently access the same data without compromising data correctness and integrity. At the same time, modifications to parallel transactions must be independent from those of other parallel transactions.
- Durability (Durability): after the transaction ends, the transaction processing result must be solidified.
In Sqlite, we use the following three paragraphs to process transactions:
- Db. beginTransaction ()
- SetTransactionSuccessful ()
- Db. endTransaction ()
Refer to the following code (lisi pays 1000 yuan to zhangsan)
?
12345678910111213141516171819 |
String str; public void testTransaction() throws Exception { PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext()); SQLiteDatabase db = helper.getWritableDatabase(); // Start database transactions 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" }); // Set the flag for successful database transaction execution db.setTransactionSuccessful(); } finally { // If the execution is successful (flag is set, commit (); otherwise, rollback rolls back db.endTransaction(); } } |
The str. equals ("123"); statement contains a null pointer error. This can be used to simulate Abnormal Program interruptions. We can check the results and find that SQL statements are not executed only in part.
Moved from my blog, xge technical blog:
Http://www.xgezhang.com/android_sqlite_transaction.html