Analysis of Database Transaction Usage in Android Development

  • 2021-07-26 08:55:15
  • OfStack

This article illustrates the usage of database transactions in Android development. Share it for your reference, as follows:

In android application development, transaction processing is very important when using databases.

First of all, Android database operations (especially write operations) are very slow, and packaging all operations into one transaction can greatly improve the processing speed.

The second is to ensure the uniformity of data, so that all operations in a transaction can be successfully executed, or failed, or all operations can be rolled back.

If you prefer to use other platforms (such as PHP + MySQL), the code usually runs on a powerful server and will not be aborted unexpectedly, but on android, you will be surprised by unexpected abortions one after another. android system will kill apps/threads/activities interrupt database use, battery power will be exhausted or removed, etc. Therefore, it is very important to use database things.

Implementing an android database transaction is straightforward, using only three methods of the SQLiteDatabase class.

beginTransaction();
setTransactionSuccessful();
endTransaction();

When endTransaction () is called, all operations starting with beginTransaction () are committed.

A simple database transaction operation is as follows:


mDatabase.beginTransaction();
try{
 // Perform multiple database operations here 
 // Exceptions may be thrown during execution 
 mDatabase.setTransactionSuccessful();
 // In setTransactionSuccessful And endTransaction Do not perform any database operations between 
 }catch(Exception e){
  // When there is an error in the database operation, you need to catch an exception and end the transaction 
  mDatabase.endTransaction();
  throwe;
 }
 // End when all operations are completed 1 Transactions 
 mDatabase.endTransaction();
}

For more readers interested in Android related contents, please check the topics on this site: "Summary of Android Database Operation Skills", "Summary of activity Operation Skills for Android Programming", "Summary of Android File Operation Skills", "Summary of SD Card Operation Methods for Android Programming Development", "Introduction and Advanced Tutorial for Android Development", "Summary of Android Resource Operation Skills", "Summary of Android View View Skill" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: