Recently, an android project encountered a problem. During app initialization, a large amount of data needs to be inserted into SQLite in batches. The for + insert method alone causes slow application response, because when SQLite inserts data, a default statement is a transaction, and disk operations are performed as many data records as possible. The first 5000 records of my application are 5000 read/write operations on the disk.
It is not guaranteed that all data can be inserted at the same time. (Some of them may be successfully inserted, and the other part may fail to be deleted later. Too troublesome)
Solution:
Add transaction processing and insert 5000 records as a transaction
We use SQLite transactions for control:
DB. begintransaction ();// Manually set start transaction
Try {
// Batch Processing
For (collection C: colls ){
Insert (dB, C );
}
DB. settransactionsuccessful(); // Sets whether the transaction is successfully processed. If this parameter is not set, automatic rollback is performed and no commit is performed.
} Catch (exception e ){
Mylog. printstacktracestring (E );
} Finally {
DB. endtransaction (); // processing completed
}
To:
1.Use sqlitedatabaseBegintransaction ()Method To start a transaction, the program runsEndtransaction ()Method will check whether the transaction flag is successful, if the program is called before the endtransaction ()Settransactionsuccessful()If the flag of the transaction is set to successful, the transaction is committed. If settransactionsuccessful is not called()
Method to roll back the transaction.
2.Example: The following two SQL statements are executed in the same transaction.
Java code
- // Bank Account Transaction Test
- PublicVoidPayment ()
- {
- SqlitedatabaseDB=Dbopenhelper. getwritabledatabase ();
- // Start the transaction
- DB. begintransaction ();
- Try
- {
- Db.exe csql ("UpdatePersonSetAmount = amount-10WherePersonid =? ",NewObject [] {1 });
- Db.exe csql ("UpdatePersonSetAmount = Amount + 10WherePersonid =? ",NewObject [] {2 });
- // Set the transaction flag to successful. When the transaction ends, the transaction will be committed.
- DB. settransactionsuccessful();
- }
- Finally
- {
- // End the transaction
- DB. endtransaction ();
- }
- }