连接关闭后 SQLite 获取最后一行 ID
我有两个功能。
一插入数据库。它打开连接并在插入后关闭它。 另一个是GetLastID函数。
我知道我可以查询最大的 ID,但我被告知这是一个不好的做法。
“选择sqlite_last_insert_rowid();”似乎没有用,因为我在插入后关闭连接。
I have two functions.
One Insert into database. It opens the connection and closes it after insert.
Other is GetLastID function.
I know I could query the biggest ID but I was told it's a bad practice.
"SELECT sqlite_last_insert_rowid();" seems no use since I'm closing the connection after Insert.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用同一连接插入数据并检索 id(无需关闭它)。
您将执行类似于以下 SQL 的操作:
然后您将必须使用命令对象
ExecuteScalar()
函数而不是ExecuteNonQuery()
来获取 rowid。请确保您的表有一个名为
ProductID
的列,通常是具有自动增量的 INTEGER 并设置为主键。You need to insert the data and retrieve the id using the same connection (without closing it).
You would do something similar to the below SQL:
then you will have to use the command objects
ExecuteScalar()
function instead ofExecuteNonQuery()
to get the rowid.Do make sure your table has a column named
ProductID
, typically INTEGER with autoincrement and set as primary key.last_insert_rowid() (以及其他数据库中的类似函数)本质上只适用于当前连接。您能否在关闭连接之前重构代码以查询 last_insert_rowid() ?
如果出于某种原因这是不可能的,我想那就只剩下查询最大的 ID 了。这被认为是不好的做法,因为之后可能会立即插入另一行,因此您不能保证您会获得您认为的行的 ID。数据库中是否还有另一列具有可以查询的唯一索引?也就是说,
当电子邮件保证唯一时,类似以下内容将是可靠的替代方案。
last_insert_rowid() (and similar functions in other databases) by their nature only work on the current connection. Can you not refactor your code to query last_insert_rowid() before closing the connection ?
If that's not possible for whatever reason, I guess that only leaves querying the biggest ID. That's regarded as bad practice, because there might have been another row inserted immediately after and so you can't guarantee you'll be getting the ID of the row you think. Is there another column in the database with a unique index that you could query on instead ? That is, something like:
would be a reliable alternative when email is guaranteed unique.
它已经解决了这个问题。
It has solved the issue.