每当我调用rawQuery()时,是否必须关闭Cursor对象?

Jen*_*nix 3 sqlite android cursor

我打算第一次使用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;
Run Code Online (Sandbox Code Playgroud)

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

  1. 我必须关闭游标之前,我打电话rawQuery()方法AGAIN

  2. 关闭游标和数据库后,我是否必须为变量赋值?

Kar*_*uri 7

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

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

关闭游标和数据库后,我是否必须为变量赋值?

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

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

...然后没有必要将它们归零,因为当方法完成执行时它们会立即超出范围.但是您的实际代码可能看起来不同.如果您有某些理由希望允许这些对象被垃圾收集,那么您可以将变量置空.