我可以使用 ODBC 获取插入行的主键吗?

发布于 2024-07-19 05:25:35 字数 542 浏览 3 评论 0原文

在 .NET 中使用 ODBC 对象时,检索插入行的主键的最佳方法是什么?

例如(VB):

Dim command As OdbcCommand = gOdbcConn.CreateCommand()
command.CommandText("INSERT INTO auhinode (node_key, node_desc) VALUES (0, 'New Node')")
...
Dim result As Integer = command.ExecuteNonQuery()

我看到了一些其他建议这里,但我想知道是否有特定于 ODBC 对象的解决方案?

编辑:我们使用 ODBC 的原因是因为我们支持 3 种不同的数据库 - SQL Server、Oracle、Informix。

What is the best way to retrieve the primary key of an inserted row, when using ODBC objects in .NET?

For example (VB):

Dim command As OdbcCommand = gOdbcConn.CreateCommand()
command.CommandText("INSERT INTO auhinode (node_key, node_desc) VALUES (0, 'New Node')")
...
Dim result As Integer = command.ExecuteNonQuery()

I've seen a couple of other suggestions here, but I'm wondering if there's solutions specific to the ODBC objects?

Edit: The reason we're using ODBC, is because we support 3 different databases - SQL Server, Oracle, Informix.

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

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

发布评论

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

评论(2

护你周全 2024-07-26 05:25:35

您不会找到一种适用于所有 3 数据库引擎的方法。 它们都有不同的方法来获取刚刚插入的行的 ID。

选择范围_身份(); 在 SQL Server 中。

在oracle中,您需要使用序列并自己将值插入表中。

Informix

所以在你的代码中你必须知道当前配置了哪个数据库才能使用所需的代码。

另一种选择是让存储过程执行插入操作,获取 ID 返回给您。 然后,您不需要对代码进行任何更改,代码调用返回 ID 的存储过程,但每个数据库引擎都有不同版本的存储过程,每个版本都具有相同的名称,并将它们包含在脚本中创建您的数据库。

You are not going to find ONE way that will work in all 3 db engines. They each have different ways of getting the ID of the row you just inserted.

select scope_identity(); in sql server.

In oracle you need to use a sequence and insert the value in the table yourself.

Informix

So in your code you are going to have to know what database is currently configured to use the required code.

Another option is to have a stored procedure do the insert, get the ID an return to you. Then you don't need to make any changes in your code, the code calls a stored procedure that returns the ID but you have different versions of the stored procedure for each db engine, each with the same name, and include them in your scripts to create your database.

哆啦不做梦 2024-07-26 05:25:35

假设数据库是 SQLServer 数据库,您所要做的就是:

 SELECT SCOPE_IDENTITY();

另外,不要使用:

 SELECT @@IDENTITY;

它是邪恶的。 好吧,这并不是真正的邪恶,但如果您有触发器或任何其他会在数据库中插入另一条记录的东西,它可能不会返回您正在寻找的 ID。

Assuming the db is a SQLServer db, all you have to do is:

 SELECT SCOPE_IDENTITY();

Also, don't use:

 SELECT @@IDENTITY;

It's evil. Ok, it's not really evil, but it may not return the ID you're looking for if you have triggers or anything else that would insert another record in your db.

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