当前位置: 首页 > 编程语言 > C#

C#LearningTutorial-Specificcastisinvalidwhenretrievingscope_identity共享

时间:2023-04-10 14:32:00 C#

Specificcastisnotvalidwhenretrievingscope_identitystringinsertQuery=@"InsertintoTender(Name,Name1,Name2)values('Val1','Val2','Val3');SelectScope_Identity();";SqlCommandcmd=newSqlCommand(insertQuery,con);cmd.ExecuteNonQuery();tenderId=(int)cmd.ExecuteScalar();为了完整起见,您的代码示例存在三个问题。1)通过调用ExecuteNonQuery和ExecuteScalar执行查询两次。因此,每次运行此函数时,都会向表中插入两条记录。你的SQL,虽然是两条不同的语句,但是会一起运行,所以你只需要调用ExecuteScalar。2)Scope_Identity()返回一个小数。可以对查询结果使用Convert.ToInt32,也可以将返回值转为decimal再转为int。3)确保在using语句中包装连接和命令对象,以便正确处理它们。使用(SqlConnection连接=newSqlConnection(connectionString)){使用(SqlCommand命令=newSqlCommand(sql,连接)){connection.Open();inttenderId=(int)(decimal)command.ExecuteScalar();试试这个:-con.Open();stringinsertQuery=@"InsertintoTender(Name,Name1,Name2)values('Val1','Val2','Val3');SelectScope_Identity();";SqlCommandcmd=newSqlCommand(insertQuery,con);tenderId=Convert.ToInt32(cmd.ExecuteScalar());编辑它应该是这样的,因为正确地指出scope_identity()返回一个数字(38,0):-tenderId=Convert.ToInt32(cmd.ExecuteScalar());注意:您仍然需要删除:-cmd.ExecuteNonQuery();首先测试如下:objectid=cmd.ExcuteScalar()设置断点,看id的类型。它可能是一个Decimal,不能直接转换为int。它需要Convert.ToInt32(cmd.ExecuteScalar());以上是C#学习教程:检索scope_identity时,特定的强制转换无效。多多关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢