如何通过索引(而不是通过 id)在 SQLite 中获取一行 [英] How to get a row in SQLite by index (not by id)

查看:34
本文介绍了如何通过索引(而不是通过 id)在 SQLite 中获取一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过它在表中的索引/位置而不是它的 id 来获取一行?

Is there a way to get a row by its index/position in table, rather than by its id?

例如我有 3 行带有 ID:

For example I have 3 rows with IDs:

Record1
Record2
Record3

现在如果我使用它的 id 删除第二行,剩下的行将是这样的:

Now if I delete the second row using its id, the remaining rows will be like this:

Record1
Record3

因为我使用 ListView 位置来确定要删除数据库中的哪一行,所以下次我尝试删除第二行时,会出现异常,因为 ID 为 2 的行不存在.

Because I'm using ListView position to determine which row in the database to delete, the next time I try to delete second row, I will get exception because row with id 2 doesn't exist.

那么有没有一种方法可以通过表中的索引检索行?

So is there a method that can retrieve row by its index in table?

推荐答案

更好的方法是从 ListView 项目表示的对象中获取记录的 id,然后使用它来在数据库中获取正确的记录.在您的 ListViewOnItemClickListener 中,onItemClick 事件将 AdapterView 作为第一个参数和所选项目作为第二个.从适配器中获取该项目并将其转换为它所代表的类型.

The better route to go will be to fetch the id of the record from the object represented by ListView item and then use that to get the correct record in the database. In your ListView's OnItemClickListener, the onItemClick event takes the AdapterView as the first argument and the index of the selected item as the second. Get that item from the adapter and cast it to the type it represents.

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    YourClass c = (YourClass)arg0.getItemAtPosition(arg2);
    //index of the record to delete can now be accessed at c.id
}

但是,如果你真的想拿到nth条记录,我相信你可以做到以下几点:

However, if you really want to get the nth record, I believe you can do the following:

SELECT * FROM TableName LIMIT 1 OFFSET n;

其中 n 是您要查找的索引.这还假设您的结果以与 ListView 中相同的方式排序.

Where n is the index you're after. This also assumes that your results are ordered in the same fashion as they are in your ListView.

这篇关于如何通过索引(而不是通过 id)在 SQLite 中获取一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆