美文网首页
SQLiteDatabase事务操作为什么一定要执行endTra

SQLiteDatabase事务操作为什么一定要执行endTra

作者: 拿拿guardian | 来源:发表于2020-06-12 16:40 被阅读0次

    只有执行了endTransaction方法,事务操作才会真正提交到数据库。
    来看源码:

        /**
         * End a transaction. See beginTransaction for notes about how to use this and when transactions
         * are committed and rolled back.
         */
        public void endTransaction() {
            acquireReference();
            try {
                getThreadSession().endTransaction(null); 
            } finally {
                releaseReference(); //做一些引用回收工作
            }
        }
    
        public void endTransaction(CancellationSignal cancellationSignal) {
            throwIfNoTransaction();
            assert mConnection != null;
    
            endTransactionUnchecked(cancellationSignal, false); 
        }
    
        private void endTransactionUnchecked(CancellationSignal cancellationSignal, boolean yielding) {
            if (cancellationSignal != null) {
                cancellationSignal.throwIfCanceled();
            }
    
            final Transaction top = mTransactionStack;
            boolean successful = (top.mMarkedSuccessful || yielding) && !top.mChildFailed; 
            //mMarkedSuccessful在setTransactionSuccessful时被标记为true
    
            RuntimeException listenerException = null;
            final SQLiteTransactionListener listener = top.mListener;
            if (listener != null) { //默认的beginTransaction方法,listener是空,这里不再分析
                try {
                    if (successful) {
                        listener.onCommit(); // might throw
                    } else {
                        listener.onRollback(); // might throw
                    }
                } catch (RuntimeException ex) {
                    listenerException = ex;
                    successful = false;
                }
            }
    
            mTransactionStack = top.mParent;
            recycleTransaction(top);
    
            if (mTransactionStack != null) {
                if (!successful) {
                    mTransactionStack.mChildFailed = true;
                }
            } else {
                try {
                    if (successful) { //如果mMarkedSuccessful被标记为true并且中途没有异常,则真正提交到数据库
                        mConnection.execute("COMMIT;", null, cancellationSignal); // might throw
                    } else { // 否则回滚
                        mConnection.execute("ROLLBACK;", null, cancellationSignal); // might throw
                    }
                } finally {
                    releaseConnection(); // might throw
                }
            }
    
            if (listenerException != null) {
                throw listenerException;
            }
        }
    

    相关文章

      网友评论

          本文标题:SQLiteDatabase事务操作为什么一定要执行endTra

          本文链接:https://www.haomeiwen.com/subject/zfhntktx.html