During application initialization, a large amount of data needs to be inserted into sqlite in batches. The for + Insert method is used separately, resulting in slow application response. Because a statement is a transaction by default when sqlite inserts data, 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:
Copy codeThe Code is as follows: db. beginTransaction (); // manually set the 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.
// No database operations are performed between setTransactionSuccessful and endTransaction.
} Catch (Exception e ){
MyLog. printStackTraceString (e );
} Finally {
Db. endTransaction (); // processing completed
}
I,Use the beginTransaction () method of SQLiteDatabase to start a transaction. When the program runs to the endTransaction () method, it checks whether the transaction flag is successful. If the program runs to the endTransaction () method () if the setTransactionSuccessful () method is called to set the transaction flag to successful, all operations starting from beginTransaction () are committed. If the setTransactionSuccessful () method is not called, the transaction is rolled back.
II,Example: The following two SQL statements are executed in the same transaction.
Java code
Copy codeThe Code is as follows: // test the Bank Account Transaction
Public void payment ()
{
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
// Start the transaction
Db. beginTransaction ();
Try
{
Db.exe cSQL ("update person set amount = amount-10 where personid =? ", New Object [] {1 });
Db.exe cSQL ("update person set amount = amount + 10 where personid =? ", New Object [] {2 });
// Set the transaction flag to successful. When the transaction ends, the transaction will be committed.
Db. setTransactionSuccessful ();
}
Catch (Exception e ){
Throw (e );
}
Finally
{
// End the transaction
Db. endTransaction ();
}
}