[英]I'm having some issues with my scope identity retrieving a ID from an identity column
I'm having some issues with my scope identity retrieving a ID from an identity column. 我的范围标识从标识列中检索ID时遇到一些问题。
This is my code: 这是我的代码:
cmd = connection.CreateCommand();
cmd.CommandText = "Insert Into oc_manufacturer (name, sort_order) Values(@name, @sort_order);SELECT CAST(scope_identity() AS int)";
cmd.Parameters.AddWithValue("@name", sManufacturer);
cmd.Parameters.AddWithValue("@sort_order", 0);
iManufacturerID = (int)cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
This is inside a try catch. 这是一个尝试陷阱。 and it hits my catch when i step through it at the 2nd last line of code.
当我在代码的最后第二行逐步通过时,它就达到了我的目标。 I am still very new to using this scope identity.
我对使用此作用域标识仍然很陌生。 Usually i would create a whole new select statement with the same variables as my insert statement.
通常,我会使用与我的插入语句相同的变量来创建一个全新的select语句。 But that is very long so truing to get this right.
但这很长,因此很努力做到这一点。 any help?
有什么帮助吗?
Perhaps I am wrong, but you have marked your question as MySql. 也许我错了,但您已将问题标记为MySql。 In that database system, you retrieve the last inserted autoincrement value with LAST_INSERT_ID() function
在该数据库系统中,使用LAST_INSERT_ID()函数检索最后插入的自动增量值
cmd.CommandText = @"Insert Into oc_manufacturer (name, sort_order)
Values(@name, @sort_order);
SELECT LAST_INSERT_ID()";
Also there is no need to call ExecuteNonQuery, the call to ExecuteScalar will work on both statements but will return the value of the last SELECT 同样也不需要调用ExecuteNonQuery,对ExecuteScalar的调用将在两个语句上都有效,但是将返回最后一个SELECT的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.