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

Do I have to close the Cursor object whenever I call rawQuery()?

我打算第一次使用 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. 是否必须像上面那样关闭游标和数据库后将空值赋给变量?

Do I have to close the cursor before I call rawQuery() method AGAIN?

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

Do I have to assign null to the variables after closing the cursor and database like above?

这取决于变量的范围。如果您的代码如下所示...

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

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