获取 SQLite 数据库的下一个 AUTO_INCRMENT 值
使用 Android API 中的典型 SQLiteDatabase 对象,我可以做什么来获取特定列(即 id
)的下一个 AUTO_INCRMENT
值,而不影响该值本身。有办法吗?或者我应该执行什么查询才能获得该结果。请记住,SQLiteDatabase.query() 返回一个 Cursor 对象,因此如果我只想从中获取值,我不太确定如何直接处理它。
Using the typical SQLiteDatabase object in Android's API, what can I do to get the next AUTO_INCREMENT
value of a particular column (ie. id
) without affecting the value itself. Is there a method for that? Or what query should I execute to get that result. Keep in mind that SQLiteDatabase.query() returns a Cursor
object, so I'm not too sure how to deal with that directly if I just want to get a value out of it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你说得对。第一个答案(仍在下面)仅在没有 id 的自动增量的情况下才有效。使用 AUTOINCRMENT,值存储在单独的表中并用于增量。这是查找值的示例:
请参阅:http://www.sqlite.org/autoinc.html
第一个答案:
您可以查询 _id 列的最大值,例如:
这适用于尚未指定为“INTEGER PRIMARY KEY AUTOINCRMENT”的行 id(所有表都有行 id 列)。
You're right. The first answer (still below) only works without an AUTOINCREMENT for id. With AUTOINCREMENT, the values are stored in a separate table and used for the increment. Here's an example of finding the value:
See: http://www.sqlite.org/autoinc.html
First Answer:
You can query for the max of the _id column, such as:
This works for row ids that haven't been specified as "INTEGER PRIMARY KEY AUTOINCREMENT" (all tables have a row id column).
获取自动增量主键上最后一个 ID 的最佳方法
这是使用 SQLITE
String query = "select seq from sqlite_sequence WHERE name = 'Table_Name'"
This is the best way to get the last ID on auto increment PRIMARY KEY with SQLITE
String query = "select seq from sqlite_sequence WHERE name = 'Table_Name'"
关于 SQLITE_SEQUENCE 表的重要说明。
文档说
因此,将创建 SQLITE_SEQUENCE 表,但不会创建与包含 AUTOINCREMENT 列的表关联的行。该行是使用第一个插入查询创建的(“seq”值为 1)。
这意味着在查找特定表的下一个自动增量值之前,您必须至少执行一次插入操作。例如,可以在创建表之后执行虚拟行的插入和删除。
An important remark about the SQLITE_SEQUENCE table.
The documentation says
So the SQLITE_SEQUENCE table is created, but NOT the row associated with the table that contains the AUTOINCREMENT column. That row is created with the first insert query (with "seq" value of 1).
That means that you must doing at least one insert operation before looking for the next autoincrement value of a specific table. It could be done for example just after the creation of the table, performing an insert and a delete of a dummy row.
以下是我用来获取特定表的下一个 AUTOINCRMENT 值的方法:
Here is what I use to get the next AUTOINCREMENT value for a specific table:
在您使用的 SQLiteOpenHelper 内,启动一个事务。插入一些数据然后回滚。
这样,您就可以获得下一行 id,如下所示:
Inside the SQLiteOpenHelper you use, start a transaction. Insert some data and then rollback.
Such a way, you 'll be able to get the next row id, like this:
这是工作。
It's work.
您可以使用
cursor.getInt(i);
方法i
这里是 id 列的索引You can use
cursor.getInt(i);
methodi
here is index of the id column