Application initialization requires a lot of data to be inserted into SQLite, and the use of the For+insert method alone causes the application to respond slowly, because when SQLite inserts the data, the default statement is a transaction, and the number of times the disk operation is there. My application initial 5,000 records that is to read and write disk operations 5,000 times.
And there is no guarantee that all data can be inserted simultaneously. (It is possible that part of the insert succeeds, another part fails, and subsequent deletions are made.) Too troublesome)
Workaround:
Add a transaction, insert 5,000 as a transaction
we use SQLite's transactions to control:
db.begintransaction (); Set up a start transaction manually
try{
//Bulk processing operations
For (Collection c:colls) {
Insert (DB, c);
}
db.settransactionsuccessful ();//Set transaction success, do not set automatically rollback does not commit
}catch (Exception e) {
mylog.printstacktracestring (e);
}finally{
db.endtransaction ();//Processing complete
}
Turn:
1. use Sqlitedatabase's BeginTransaction () method to open a transaction, the program executes to endtransaction () The Endtransaction method checks whether the flag for the transaction is successful, if the program executes to the settransactionsuccessful ( ) method before the call to set the transaction flag as successful commits the transaction, If the Settransactionsuccessful () method is not called, the transaction is rolled back.
2. examples of use are as follows: The following two SQL statements are executed in the same transaction.
Java Code
- Bank account Transaction Testing
- public void Payment ()
- {
- Sqlitedatabase db = Dbopenhelper.getwritabledatabase ();
- Open transaction
- Db.begintransaction ();
- Try
- {
- Db.execsql ("Update person set amount=amount-10 where personid=?", New Object[]{1});
- Db.execsql ("Update person set amount=amount+10 where personid=?", New object[]{2});
- The transaction flag is set to be successful, and the transaction is committed when the transaction is ended
- Db.settransactionsuccessful ();
- }
- Finally
- {
- End transaction
- Db.endtransaction ();
- }
- }
Android SQLite Transaction Processing