SQLite中所有SQL语句都需要先编译为stmt,然后执行。
首先看一个SQLiteDatabase.update()的过程。
// SQLiteDatabase.java public int update(String table, ContentValues values, String whereClause, String[] whereArgs) { return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE); } public int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm) { acquireReference(); try { // 构造sql语句 ...... SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs); try { return statement.executeUpdateDelete(); } finally { statement.close(); } } finally { releaseReference(); } } // SQLiteStamente.java public int executeUpdateDelete() { acquireReference(); try { return getSession().executeForChangedRowCount( getSql(), getBindArgs(), getConnectionFlags(), null); } catch (SQLiteDatabaseCorruptException ex) { onCorruption(); throw ex; } finally { releaseReference(); } } // SQLiteSeesion.java public int executeForChangedRowCount(String sql, Object[] bindArgs, int connectionFlags, CancellationSignal cancellationSignal) { ...... acquireConnection(sql, connectionFlags, cancellationSignal); try { return mConnection.executeForChangedRowCount(sql, bindArgs, cancellationSignal); } finally { releaseConnection(); } } // SQLiteConnection.java public int executeForChangedRowCount(String sql, Object[] bindArgs, CancellationSignal cancellationSignal) { ...... try { final PreparedStatement statement = acquirePreparedStatement(sql); try { ...... try { // !!! 开始执行 实质为调用jni中的executeNonQuery changedRows = nativeExecuteForChangedRowCount( mConnectionPtr, statement.mStatementPtr); return changedRows; } finally { detachCancellationSignal(cancellationSignal); } } finally { releasePreparedStatement(statement); } } catch (RuntimeException ex) { mRecentOperations.failOperation(cookie, ex); throw ex; } finally { if (mRecentOperations.endOperationDeferLog(cookie)) { mRecentOperations.logOperation(cookie, "changedRows=" + changedRows); } } }
public final class SQLiteStatement extends SQLiteProgram { SQLiteStatement(SQLiteDatabase db, String sql, Object[] bindArgs) { super(db, sql, bindArgs, null); } } public abstract class SQLiteProgram extends SQLiteClosable { private static final String[] EMPTY_STRING_ARRAY = new String[0]; private final SQLiteDatabase mDatabase; private final String mSql; private final boolean mReadOnly; private final String[] mColumnNames; private final int mNumParameters; private final Object[] mBindArgs; } private static final class PreparedStatement { public PreparedStatement mPoolNext; public String mSql; public int mStatementPtr; // 指向native中stmt的指针 public int mNumParameters; public int mType; public boolean mReadOnly; public boolean mInCache; public boolean mInUse; }
SQLiteProgram(SQLiteDatabase db, String sql, Object[] bindArgs, CancellationSignal cancellationSignalForPrepare) { mDatabase = db; mSql = sql.trim(); int n = DatabaseUtils.getSqlStatementType(mSql); switch (n) { case DatabaseUtils.STATEMENT_BEGIN: case DatabaseUtils.STATEMENT_COMMIT: case DatabaseUtils.STATEMENT_ABORT: mReadOnly = false; mColumnNames = EMPTY_STRING_ARRAY; mNumParameters = 0; break; default: boolean assumeReadOnly = (n == DatabaseUtils.STATEMENT_SELECT); SQLiteStatementInfo info = new SQLiteStatementInfo(); db.getThreadSession().prepare(mSql, db.getThreadDefaultConnectionFlags(assumeReadOnly), cancellationSignalForPrepare, info); mReadOnly = info.readOnly; mColumnNames = info.columnNames; mNumParameters = info.numParameters; break; } if (bindArgs != null && bindArgs.length > mNumParameters) { throw new IllegalArgumentException("Too many bind arguments. " + bindArgs.length + " arguments were provided but the statement needs " + mNumParameters + " arguments."); } if (mNumParameters != 0) { mBindArgs = new Object[mNumParameters]; if (bindArgs != null) { System.arraycopy(bindArgs, 0, mBindArgs, 0, bindArgs.length); } } else { mBindArgs = null; } }
//SQLiteSeesion.java public void prepare(String sql, int connectionFlags, CancellationSignal cancelationSignal, SQLiteStatementInfo outStatementInfo) { acquireConnection(sql, connectionFlags, cancellationSignal); try { mConnection.prepare(sql, outStatementInfo); } finally { releaseConnection(); } } // SQLiteConnection.java public void prepare(String sql, SQLiteStatementInfo outStatementInfo) { try { final PrepraedStatement statement = acquirePreparedStatement(sql); try { if (outStatementInfo != null) { outStatementInfo.numParameters = statement.mNumParameters; outStatementInfo.readOnly = statement.mReadOnly; final int columnCount = nativeGetColumnCount(// native得到结果的列的个数 mConnectionPtr, statement.mStatementPtr); if (columnCount == 0) { outStatementInfo.columnNames = EMPTY_STRING_ARRAY; } else { outStatementInfo.columnNames = new String[olumnCount]; //native获取列的名称 for (int i = 0; i < columnCount; i++) { outStatementInfo.columnNames[i] = nativeGetColumnName( mConnectionPtr, statement.mStatementPtr, i); } } } } finally { releasePreparedStatement(statement); } } catch (RuntimeException ex) { mRecentOperations.failOperation(cookie, ex); throw ex; } finally { mRecentOperations.endOperation(cookie); } } private PreparedStatement acquirePreparedStatement(String sql) { PreparedStatement statement = mPreparedStatementCache.get(sql); boolean skipCache = false; if (statement != null) { // 如果缓存中存在 if (!statement.mInUse) { // 并且不在使用中 return statement; // 返回该statement } skipCache = true; // 如果已在使用 另备一份并不再缓存 } final int statementPtr = nativePrepareStatement(mConnectionPtr, sql); //native try { final int numParameters = nativeGetParameterCount(mConnectionPtr, statementPtr); final int type = DatabaseUtils.getSqlStatementType(sql); final boolean readOnly = nativeIsReadOnly(mConnectionPtr, statementPtr); statement = obtainPreparedStatement(sql, statementPtr, numParameters, type, readOnly); if (!skipCache && isCacheable(type)) { mPreparedStatementCache.put(sql, statement); // 将statement放入缓存中 statement.mInCache = true; } } catch (RuntimeException ex) { if (statement == null || !statement.mInCache) { nativeFinalizeStatement(mConnectionPtr, statementPtr); } throw ex; } statement.mInUse = true; return statement; }
private final class PreparedStatementCache extends LruCache<String, PreparedStatement> { public PreparedStatementCache(int size) { super(size); } } private PreparedStatement obtainPreparedStatement(String sql, int statementPtr, int numParameters, int type, boolean readOnly) { // 从池中获取一个statement,并将其从池中移除 PreparedStatement statement = mPreparedStatementPool; if (statement != null) { // mPreparedStatementPool = statement.mPoolNext; statement.mPoolNext = null; statement.mInCache = false; } else { statement = new PreparedStatement(); } statement.mSql = sql; statement.mStatementPtr = statementPtr; statement.mNumParameters = numParameters; statement.mType = type; statement.mReadOnly = readOnly; return statement; }
private void releasePreparedStatement(PreparedStatement statement) { statement.mInUse = false; if (statement.mInCache) { // 如果在缓存中重置stmt nativeResetStatementAndClearBindings(mConnectionPtr, statement.mStatementPtr); } else {// 如果不在缓存,即缓存中已经有相同一份 finalizePreparedStatement(statement); } } private void finalizePreparedStatement(PreparedStatement statement) { // 销毁指向的stmt nativeFinalizeStatement(mConnectionPtr, statement.mStatementPtr); // 将statement放入mPreparedStatementPool recyclePreparedStatement(statement); } private void recyclePreparedStatement(PreparedStatement statement) { statement.mSql = null; statement.mPoolNext = mPreparedStatementPool; mPreparedStatementPool = statement; }
① 每个connection维护着多个PreparedStatement,可以直接使用的在缓存中,只有外壳没有stmt已被销毁的放在池中。
② SQLiteStatement prepare时,多次调用到connection中,先在缓存中获取相应PreparedStatement,如果获取不到在池中获取只有外壳的PreparedStatement对其重新构建。
③ SQLiteStatement 执行时,通过acquireConnection获取到最佳connection,通过connection执行相应PreparedStatement;如果不巧最佳connection被其他线程抢走,不含相应PreparedStatement的connection会先行构建PreparedStatement,然后执行。