检索scope_identity时,特定转换无效
我收到异常:“特定演员无效”,这是代码
con.Open();
string insertQuery = @"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
tenderId = (int)cmd.ExecuteScalar();
I am getting exception: "Specific cast is not valid", here is the code
con.Open();
string insertQuery = @"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
tenderId = (int)cmd.ExecuteScalar();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了完整起见,您的代码示例存在三个问题。
1) 您通过调用
ExecuteNonQuery
和ExecuteScalar
执行查询两次。因此,每次运行此函数时,您都会在表中插入两条记录。尽管您的 SQL 是两个不同的语句,但它们将一起运行,因此您只需调用ExecuteScalar
。2)
Scope_Identity()
返回小数。您可以对查询结果使用Convert.ToInt32
,也可以将返回值转换为十进制,然后转换为 int。3) 确保将连接和命令对象包装在
using
语句中,以便正确处理它们。In the interests of completeness, there are three issues with your code sample.
1) You are executing your query twice by calling
ExecuteNonQuery
andExecuteScalar
. As a result, you will be inserting two records into your table each time this function runs. Your SQL, while being two distinct statements, will run together and therefore you only need the call toExecuteScalar
.2)
Scope_Identity()
returns a decimal. You can either useConvert.ToInt32
on the result of your query, or you can cast the return value to decimal and then to int.3) Be sure to wrap your connection and command objects in
using
statements so they are properly disposed.试试这个:-
编辑
应该是这样,因为它正确指出了scope_identity() 返回一个数字(38,0) :-
注意: 您仍然需要删除这:-
Try this:-
EDIT
It should be this as it is correctly pointed out that scope_identity() returns a numeric(38,0) :-
Note: You still need to remove the:-
首先测试以下内容:
设置断点并查看
id
的类型。它可能是一个Decimal
并且不能直接转换为int
。Test the following first:
Set a break point and have a look at the type of
id
. It is probably aDecimal
and cannot directly be casted toint
.它需要 Convert.ToInt32(cmd.ExecuteScalar());
it needs Convert.ToInt32(cmd.ExecuteScalar());