问题
I have to provide synchronization when inserting, querying, updating and deleting items from a database. As far as I understand beginTransaction()
and beginTransactionNonExclusive()
are the methods I need.
Besides SQLite documentation describes EXCLUSIVE
, IMMEDIATE
, and DEFERRED
quite well.
Transactions can be deferred, immediate, or exclusive. Deferred means that no locks are acquired on the database until the database is first accessed.
If the transaction is immediate, then RESERVED locks are acquired on all databases as soon as the BEGIN command is executed, without waiting for the database to be used. After a BEGIN IMMEDIATE, no other database connection will be able to write to the database or do a BEGIN IMMEDIATE or BEGIN EXCLUSIVE. Other processes can continue to read from the database, however.
An exclusive transaction causes EXCLUSIVE locks to be acquired on all databases. After a BEGIN EXCLUSIVE, no other database connection except for read_uncommitted connections will be able to read the database and no other connection without exception will be able to write the database until the transaction is complete.
It seems to provide some protection from unwanted insertions and queries while some thread is working with the database. But I'm not sure that it guarantees synchronization.
There is the insert
method of my ContentProvider
.
@Override
public Uri insert(Uri baseUri, ContentValues values) {
try {
mDatabase = mHelper.getWritableDatabase();
mDatabase.beginTransaction(); // EXCLUSIVE
switch (sUriMatcher.match(baseUri)) {
case UriCodes.COUNTRIES:
case UriCodes.CONTINENTS:
case UriCodes.ORGS:
String table = baseUri.getLastPathSegment();
long rowId = mDatabase.insert(table, null, values);
Uri uri = Uri.withAppendedPath(baseUri, Long.toString(rowId));
mDatabase.setTransactionSuccessful();
return uri;
default:
mDatabase.endTransaction();
throw new IllegalArgumentException(UNSUPPORTED_URI + SPACE + baseUri);
}
} finally {
mDatabase.endTransaction();
}
}
I haven't had any problems without beginTransaction()
, endTransaction()
, and setTransactionSuccessful()
before. Do I really need to add them?
回答1:
Off course with Android! If you are working for reliable data manipulation then it is important to use following supported methods.
BeginTransaction();
SetTransactionSuccessful();
EndTransaction();
For further see this…In android it is highly important to use transactions when working with databases.
回答2:
Yes, it makes app smooth.Because SQLite consider one cursor as one transaction, so if we use begin transaction() before we insert big amount of data, then use setTransactionSuccessful() second, then endTransaction() in finally, SQLite will consider this insert event as one transaction, instead of hundreds of transactions.
来源:https://stackoverflow.com/questions/16564000/begintransaction-endtransaction-and-settransactionsuccessful-what-exact