.net SQLCommand.ExecuteScalar()-为什么它会引发System.NullReferenceException?
是否有人注意到以下功能可能有什么问题:.net SQLCommand.ExecuteScalar()-为什么它会引发System.NullReferenceException?,.net,exception,sqlcommand,.net,Exception,Sqlcommand,是否有人注意到以下功能可能有什么问题: public string Login(string username, string password) { string result = ""; string select = "SELECT user_id FROM [user] WHERE username = @username AND password = @password"; SqlConnection conn = new Sql
public string Login(string username, string password)
{
string result = "";
string select = "SELECT user_id FROM [user] WHERE username = @username AND password = @password";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(select, conn);
cmd.Parameters.AddWithValue("username", username);
cmd.Parameters.AddWithValue("password", password);
int userID = 0;
try
{
conn.Open();
userID = (int)cmd.ExecuteScalar();
if(userID > 0)
{
result = addSession(userID);
}
}
catch(Exception ex)
{
string sDummy = ex.ToString();
}
return result;
}
不知道为什么行`userID=(int)cmd.ExecuteScalar();抛出异常
谢谢
你应该考虑修改这段代码:try
{
conn.Open();
userID = (int)cmd.ExecuteScalar();
if(userID > 0)
{
result = addSession(userID);
}
}
catch(Exception ex)
{
string sDummy = ex.ToString();
}
finally // add this to ensure the connection is closed!
{
if (conn != null)
conn.Close();
}
不确定,但参数名称可能需要“@”:
...AddWithValue("@username", username);
如果在数据库中找不到提供的凭据,标量是否可能为null?表中很可能没有包含该用户/密码的行。的文档说,如果结果集为空,它将返回null,并且不能将null强制转换为int。我在使用SqlCE时也遇到了同样的问题。我找到的解决方案(在我开始正确输入密码之后…>。>)是首先收集ExecuteScalar结果作为对象,然后转换。随地使用
Object o = cmd.ExecuteScalar();
int id = Convert.ToInt32(o);
而不是
int id = (int) cmd.ExecuteScalar();
是工作和崩溃之间的区别。我不知道为什么…我没有看到任何hashbytes函数,但它是这样的: 如果在后端SQL server上使用
hashbytes
函数,请将密码输入转换为二进制数组。
Hashbytes返回varbinary。因此,如果传递空终止符,则散列将不相同。类似于SQL中的hashbytes('SHA2_512,'stuff')类似于散列's','t',直到'f'。末尾没有“\0”。但是,如果在sqlcommand对象中参数化为字符串,它将在末尾添加“\0”,SQL将计算该值为零。因此,如果使用编码
类将参数转换为二进制数组,则该参数将仅为不带空终止符的字符串。
我遇到了一个类似的问题,我通过这种方式解决了,使用addwithvalue
及其二进制值
但是,您知道executescalar返回一个对象。如果查询返回零行,则对象将为NULL,并且不能将NULL对象强制转换或转换为任何内容。因此,在if语句中说“if returningobject==null,则您未被授权。否则……”您应该发布完整的异常,包括任何InnerException。为避免另一个问题,请将字段“password”括在方括号中,因为这也是一个保留字。调用ExecuteScalar时的良好实践是确保查询返回结果。查询可以更改为:从[user]中选择ISNULL(MAX(user\u id),-1)。。。