本文介绍了请问SqlCommand的方法的ExecuteScalar()返回的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL Server中,ID是一个非空整数,一个身份。

当我运行下面的code,我得到的最后一行一个InvalidCastException:

 的SqlCommand CMD =新的SqlCommand();
cmd.Connection = _conn;
cmd.CommandText = @INSERT INTO [用户](姓名,电子邮件,密码)VALUES(@name,@Email,@pass);选择SCOPE_IDENTITY();
cmd.Parameters.AddWithValue(@名,newUser.Name);
cmd.Parameters.AddWithValue(@电子邮件,newUser.Email);
cmd.Parameters.AddWithValue(@通,newUser.PasswordHash);
INT的id =(int)的cmd.ExecuteScalar();
 

什么是的ExecuteScalar()返回这里?无论其返回拥有的ToString(),使得它看起来像一个数字,所以code这个可怕的线路工作:

 内部ID = Int32.Parse(cmd.ExecuteScalar()的ToString());
 

解决方案

SCOPE_IDENTITY()返回十进制的code,也称为数字(38,0)的TSQL

http://msdn.microsoft.com/en-us/library/ms190315.aspx

所以,如果你想有一个直接的转换,你可以做(INT)(十进制)cmd.ExecuteScalar(); 。需要注意的是十进制为int的转换可能会丢失在严格意义上的信息,所以只被告知。但随着您的身份列是一个整数,则转换将是安全的。

In SQL Server, ID is a not null integer, and an identity.

When I run the following code, I get an InvalidCastException on the last line:

SqlCommand cmd = new SqlCommand();
cmd.Connection = _conn;
cmd.CommandText = @"INSERT INTO [Users] (Name, Email, Password) VALUES (@name, @email, @pass); SELECT SCOPE_IDENTITY()";
cmd.Parameters.AddWithValue("@name", newUser.Name);
cmd.Parameters.AddWithValue("@email", newUser.Email);
cmd.Parameters.AddWithValue("@pass", newUser.PasswordHash);
int id = (int)cmd.ExecuteScalar();

What is ExecuteScalar() returning here? Whatever its returning has a ToString() that makes it look like a number, so this awful line of code works:

int id = Int32.Parse(cmd.ExecuteScalar().ToString());
解决方案

SCOPE_IDENTITY() returns a decimal in code, otherwise known as NUMERIC(38,0) in TSQL.

http://msdn.microsoft.com/en-us/library/ms190315.aspx

So if you want a direct cast, you can do (int)(decimal)cmd.ExecuteScalar();. Note that a decimal to int conversion can lose information in the strictest sense, so just be advised. But with your identity column being an integer, the conversion will be safe.

这篇关于请问SqlCommand的方法的ExecuteScalar()返回的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 22:44