本文介绍了SQLCommand.ExecuteScalar() - 为什么它抛出一个System.NullReferenceException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以发现这可能是错误的以下功能:
Could anyone notice what could be wrong with the following function:
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;
}
不知道为什么行`用户ID =(INT)cmd.ExecuteScalar();抛出一个异常。
Don't know why the line `userID = (int)cmd.ExecuteScalar(); throws an exception.
感谢
推荐答案
很可能是在表中没有行与该用户/密码。该文档的的ExecuteScalar 说它返回null,如果结果集是空的,你可以不投空为int。
Most likely there is no row in the table with that user/password. The docs for ExecuteScalar say that it returns null if the result set is empty, and you can't cast null to int.
这篇关于SQLCommand.ExecuteScalar() - 为什么它抛出一个System.NullReferenceException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!