我正在使用:
string selectString =
"SELECT username, password " +
"FROM users " +
"WHERE username = '" + user + "' AND password = '" + password + "'";
MySqlCommand mySqlCommand = new MySqlCommand(selectString, Program.mySqlConnection);
Program.mySqlConnection.Open();
String strResult = String.Empty;
strResult = (String)mySqlCommand.ExecuteScalar();
Program.mySqlConnection.Close();
if (strResult.Length == 0)
{
responseString = "invalid";
InvalidLogin = true;
} else {
InvalidLogin = false;
}
并且在strResult.Length由于某种原因我得到NullReferenceException。
答案 0 :(得分:3)
这就是你的代码的样子:
using(var connection = new MySQLConnection(connectionString))
{
using(var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT COUNT(*)
FROM users
WHERE username = @user AND password = @password";
command.Parameters.Add(new MySQLParameter("user", user));
command.Parameters.Add(new MySQLParameter("password", password));
var total = (int)command.ExecuteScalar();
if(total == 0)
InvalidLogin = true;
else
InvalidLogin = false;
}
}
有几件事需要注意
using
关键字
连接和命令。要回答您的问题,问题出在您正在使用的ExecuteScalar中。它返回标量变量(单值)...在您的查询中,您返回用户名和密码,因此您应该使用ExecuteReader ...但我认为我发布的查询中的COUNT(*)可能与ExecuteScalar一起是一个更好的解决方案。
答案 1 :(得分:2)
试试这个..
string selectString =
"SELECT username, password " +
"FROM users " +
"WHERE username = '" + user + "' AND password = '" + password + "'";
MySqlCommand mySqlCommand = new MySqlCommand(selectString, Program.mySqlConnection);
Program.mySqlConnection.Open();
String strResult = String.Empty;
if (mySqlCommand.ExecuteScalar()== NULL)
{
responseString = "invalid";
InvalidLogin = true;
} else {
InvalidLogin = false;
}
Program.mySqlConnection.Close();
答案 2 :(得分:1)
ExecuteScalar()
返回单个值。您想要ExecuteReader()
,因为您要带回用户名和密码