【问题标题】:Do I have to close the Cursor object whenever I call rawQuery()?每次调用 rawQuery() 时都必须关闭 Cursor 对象吗?
【发布时间】:2015-08-07 20:21:17
【问题描述】:

我打算第一次使用 Android SQLite。

Cursor c = db.rawQuery("some select command here", null);

// some jobs with the cursor..

c = db.rawQuery("another select command here", null);

// some jobs with the cursor..

c.close();
db.close();

c = null;
db = null;

如您所见,我尝试多次调用 rawQuery() 方法。

  1. 在调用 rawQuery() 方法之前是否必须关闭光标AGAIN

  2. 像上面那样关闭游标和数据库后是否必须为变量分配null?

【问题讨论】:

    标签: android sqlite cursor


    【解决方案1】:

    在我再次调用 rawQuery() 方法之前是否必须关闭光标?

    读完后关闭光标。这是为了释放游标打开的资源,所以是的,你应该在第二个查询之前关闭第一个游标。

    像上面一样关闭游标和数据库后是否必须为变量分配null?

    这取决于变量的范围。如果你的代码看起来像这样......

    class Foo {
        void doSomething() {
            SQLiteDatabase db = ...
            Cursor c = db.rawQuery...
            // other stuff
            c.close();
            db.close();
        }
    }
    

    ...那么将它们归零真的没有意义,因为当方法完成执行时它们将立即超出范围。但是您的实际代码可能看起来不同。如果您出于某种原因希望允许对这些对象进行垃圾回收,那么您可以将变量清空。

    【讨论】:

    • 非常感谢 Karakuri!
    猜你喜欢
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2018-10-09
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多