* There are two kinds of transaction: implicit transactions and explicit * transactions. * </p><p> * An implicit transaction is created whenever a database operation is requested * and there is no explicit transaction currently in progress. An implicit transaction * only lasts for the duration of the database operation in question and then it * is ended. If the database operation was successful, then its changes are committed. * </p><p> * An explicit transaction is started by calling {@link #beginTransaction} and * specifying the desired transaction mode. Once an explicit transaction has begun, * all subsequent database operations will be performed as part of that transaction. * To end an explicit transaction, first call {@link #setTransactionSuccessful} if the * transaction was successful, then call {@link #end}. If the transaction was * marked successful, its changes will be committed, otherwise they will be rolled back. * </p><p> * Explicit transactions can also be nested. A nested explicit transaction is * started with {@link #beginTransaction}, marked successful with * {@link #setTransactionSuccessful}and ended with {@link #endTransaction}. * If any nested transaction is not marked successful, then the entire transaction * including all of its nested transactions will be rolled back
* when the outermost transaction is ended.
for example:----------------------
db.execSQL("update person set amount=amount-10 where personid=?", new Object[]{1});
or.....
- 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});
- //设置事务标志为成功,当结束事务时就会提交事务
- db.setTransactionSuccessful();
- }
- catch(Exception e){
- throw(e);
- }
- finally
- {
- //结束事务
- db.endTransaction();
- }
本文深入探讨了数据库操作中的两种事务类型:隐式事务和显式事务。隐式事务在每次数据库操作时自动创建并仅持续到该操作完成。显式事务则由程序员通过特定API调用开始,所有后续操作都作为该事务的一部分,直到明确标记成功或失败。文章还介绍了如何使用显式事务进行嵌套,以及在不同情况下的提交和回滚机制。
834

被折叠的 条评论
为什么被折叠?



