Android Tutorial

(avery) #1
Android Tutorial 307

public void deleteBooksByAuthor(Integer authorID) {
int numBooksDeleted = mDatabase.delete(“tbl_books”,
“authorid=?”, new String[] { authorID.toString() });
}

Working with Transactions

Often you have multiple database operations you want to happen
all together or not at all. You can use SQL Transactions to group
operations together; if any of the operations fails, you can handle
the error and either recover or roll back all operations. If the
operations all succeed, you can then commit them. Here we have
the basic structure for a transaction:

mDatabase.beginTransaction();
try {
// Insert some records, updated others, delete a few
// Do whatever you need to do as a unit, then commit it
mDatabase.setTransactionSuccessful();
} catch (Exception e) {
// Transaction failed. Failed! Do something here.
// It‟s up to you.
} finally {
mDatabase.endTransaction();
}


Now let’s look at the transaction in a bit more detail. A transaction
always begins with a call to beginTransaction() method and a
try/catch block. If your operations are successful, you can commit
your changes with a call to the setTransactionSuccessful() method.
If you do not call this method, all your operations are rolled back
and not committed. Finally, you end your transaction by calling
endTransaction(). It’s as simple as that.

In some cases, you might recover from an exception and continue
with the transaction. For example, if you have an exception for a
Free download pdf