连接关闭后 SQLite 获取最后一行 ID

发布于 2024-12-09 09:11:35 字数 159 浏览 0 评论 0原文

我有两个功能。

一插入数据库。它打开连接并在插入后关闭它。 另一个是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 技术交流群。

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

发布评论

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

评论(3

断桥再见 2024-12-16 09:11:35

您需要使用同一连接插入数据并检索 id(无需关闭它)。

您将执行类似于以下 SQL 的操作:

string sql = "Insert into Product (Name) values(@Name); SELECT last_insert_rowid() AS ProductID;";

然后您将必须使用命令对象 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:

string sql = "Insert into Product (Name) values(@Name); SELECT last_insert_rowid() AS ProductID;";

then you will have to use the command objects ExecuteScalar() function instead of ExecuteNonQuery() to get the rowid.

Do make sure your table has a column named ProductID, typically INTEGER with autoincrement and set as primary key.

热情消退 2024-12-16 09:11:35

last_insert_rowid() (以及其他数据库中的类似函数)本质上只适用于当前连接。您能否在关闭连接之前重构代码以查询 last_insert_rowid() ?

如果出于某种原因这是不可能的,我想那就只剩下查询最大的 ID 了。这被认为是不好的做法,因为之后可能会立即插入另一行,因此您不能保证您会获得您认为的行的 ID。数据库中是否还有另一列具有可以查询的唯一索引?也就是说,

SELECT id FROM users WHERE email = '[email protected]'

当电子邮件保证唯一时,类似以下内容将是可靠的替代方案。

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:

SELECT id FROM users WHERE email = '[email protected]'

would be a reliable alternative when email is guaranteed unique.

不奢求什么 2024-12-16 09:11:35
SELECT seq FROM sqlite_sequence where name=@Table

它已经解决了这个问题。

SELECT seq FROM sqlite_sequence where name=@Table

It has solved the issue.

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