Use the Sqlitedatabase BeginTransaction () method to open a transaction that checks whether the transaction's flag is successful if the program executes to the Endtransaction () method, if the program executes to Endtransaction () The Settransactionsuccessful () method was previously invoked to set the transaction's flag for success commits the transaction and rolls back the transaction if the Settransactionsuccessful () method is not invoked.
code is as follows |
copy code |
public void Payment () { Sqlitedatabase db = Dbopenhelper.getreadabledatabase (); Db.begintransaction ()//Start transaction try { Db.execsql ("Update person set amount=amount-10 where personid=2"); Db.execsql ("Update person set amount=amount+10 where personid=5"); Db.settransactionsuccessful ();//Set the transaction's flag to true, calling this method executes the transaction to the Endtransaction () method if the method is not called before executing to the Endtransaction () method to roll back the transaction. } catch (SQLException e) { } finally { db.endtransaction (); } //End transaction, in two cases: Commit,rollback, //transaction commit or rollback is determined by the flag of the transaction, if the transaction's flag is true, or rollback, by default the transaction's flag is False } |
Application initialization requires a lot of data to be injected into the SQLite, and a separate use of the For+insert method causes the application to respond slowly because the default statement of the SQLite when inserting data is a transaction and how many times disk operations there are. The first 5,000 records of my application are 5,000 read and write disk operations.
And there's no guarantee that all data can be plugged in at the same time
Plus transaction processing, 5,000 inserts as a transaction
We use SQLite transactions for control:
The code is as follows |
Copy Code |
Db.begintransaction (); Set Start transaction manually try{ Bulk processing operations for (Collection c:colls) { Insert (db, C); } Db.settransactionsuccessful (); Set transaction success, no setting will automatically rollback uncommitted }catch (Exception e) { Mylog.printstacktracestring (e); }finally{ Db.endtransaction (); Processing complete } |