android:关闭光标后我们需要关闭Db吗?

时间:2011-08-17 02:59:55

标签: android sqlite

从SQLiteCursor的源代码(堆栈跟踪):

at android.database.sqlite.SQLiteDatabase.dbclose(Native Method)
at android.database.sqlite.SQLiteDatabase.onAllReferencesReleased(SQLiteDatabase.java:325)
at android.database.sqlite.SQLiteClosable.releaseReference(SQLiteClosable.java:45)
at android.database.sqlite.SQLiteProgram.onAllReferencesReleased(SQLiteProgram.java:119)
at android.database.sqlite.SQLiteClosable.releaseReference(SQLiteClosable.java:45)
at android.database.sqlite.SQLiteProgram.close(SQLiteProgram.java:296)
at android.database.sqlite.SQLiteQuery.close(SQLiteQuery.java:136)
at android.database.sqlite.SQLiteCursor.close(SQLiteCursor.java:506)

这是否意味着,关闭最后一个光标也将关闭数据库。我们不需要明确地关闭它,就像在这段代码中一样:

    SQLiteDatabase rdb = db.getReadableDatabase();
    Cursor resultCursor = null;
    String patternQuery = SQLiteQueryBuilder.buildQueryString(true, "Store", columns, where, null, null, null, null);

    try
    {
        resultCursor = rdb.rawQuery(patternQuery, null);


        resultCursor.moveToFirst();
        if (resultCursor.getCount() > 0)
        {
            while (!resultCursor.isAfterLast())
            {
                result.add(resultCursor.getString(0));
                resultCursor.moveToNext();
            }
        }
    }
    catch (Exception e)
    {
        Log.d("DB", "Caught an exception while getting pattern based results: " + e);
    }
    finally
    {
        if (resultCursor != null)
        {
            resultCursor.close();
        }
        if (rdb.isOpen())
        {
            rdb.close();
        }
    }

所以在这里,我们不需要关闭rdb?

注意:游标对象保留对数据库的引用,因此它在每个查询上都获得相同的锁定。因此'SQLiteDatabse.dbclose'有效地关闭了同一个数据库。

1 个答案:

答案 0 :(得分:2)

你需要关闭它。在明确关闭所有活动游标已关闭之前,数据库不会关闭。