SQLite数据库和游标

发布于 2024-10-26 17:21:28 字数 538 浏览 0 评论 0原文

我想知道是否有人可以给我简要介绍一下 Android 光标。几个具体问题:

1 - 我有一个在数据库查询后返回游标的方法:

    public static Cursor getVehicles()
{
    SQLiteDatabase db = vehicleData.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, GET_VEHICLES_FROM_CLAUSE, null, null, null, null, ORDER_BY);

    return cursor;
}

为了进行内务处理,我在 return 语句之前尝试了 db.close() 。但是,这导致返回的游标不包含任何行。这是为什么呢?

2 - 关闭游标和关闭数据库有什么区别?

3 - 如果 Cursor 是局部变量,我是否需要调用 close,或者我可以将其留给垃圾收集器来清理吗?

4 - 我的数据库很小,仅由我的应用程序使用 - 我可以保持它打开吗?

I was wondering if someone could give me a brief overview of Android Cursors. A couple of specific questions:

1 - I have a method which returns a cursor after a database query:

    public static Cursor getVehicles()
{
    SQLiteDatabase db = vehicleData.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, GET_VEHICLES_FROM_CLAUSE, null, null, null, null, ORDER_BY);

    return cursor;
}

In order to do housekeeping, I tried db.close() just before the return statement. However, this caused the returned cursor to contain no rows. Why is this?

2 - What's the difference between closing a cursor and closing a database?

3 - Do I need to call close on a Cursor if it is a local variable, or can I leave it to the garbage collector to clean up?

4 - My database is small and only used by my application - can I just keep it open?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

碍人泪离人颜 2024-11-02 17:21:28

1) 游标只是指向查询返回的数据的指针,它不包含查询中的所有数据。这是为了提高性能/效率(不会立即读取大型结果集 -> 使用更少的内存)。因此,如果关闭数据库,游标就无法检索到数据->它是空的。

2)当关闭游标时,所有关联的资源都被释放->您无法访问与此游标关联的数据(因为它已被释放),但您可以使用此游标或其他游标进行新查询。关闭数据库后,您将无法再查询它(直到重新打开它)。

3) 始终关闭游标。否则你会遇到问题——如果游标没有关闭并且新的查询被阻止,GC 会抱怨。

4)如果您在应用程序完成后关闭它,是的。

1) The cursor is just a pointer to the data returned by your query, it doesn't contain all the data from your query. This is to increase performance/efficiency (large resultsets aren't read at once -> less memory used). Therefore, if you close the database, the cursor can't retrieve the data -> it's empty.

2) When you close a cursor, all associated resources are released -> you can't access the data associated with this cursor (since it has been released), but you can make new queries using this or other cursors. When you close a database, you can't query it anymore (until you re-open it).

3) Always close cursors. Otherwise you will run into problems - the GC will complain if the cursor isn't closed and new queries are blocked.

4) If you close it when your app finishes, yes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文