我正在使用:
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。
最佳答案
你的代码应该是这样的:
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;
}
}
有几点需要注意
- 切勿以您的方式构建查询字符串。在 Google 上搜索“sql injection” 找到更多关于你可能发生的事情。总是使用 参数。我知道,您写道这是控制台应用程序,但良好的习惯很重要。
- 在处理数据库时始终使用
using
关键字 连接和命令。 - 从您的代码中,我感觉您拥有全局 MySQLConnection 对象,对吗?永远不要那样做! ADO.NET 使用连接池,因此为您的操作打开新连接不是昂贵的操作。确保您没有在连接字符串中禁用连接池。
- 与 ADO.NET 无关,但很重要:您应该散列您的密码。
要回答您的问题,问题出在您正在使用的 ExecuteScalar 中。它返回标量变量(单值)...在您的查询中,您返回用户名和密码,因此您应该改用 ExecuteReader ...但我认为我发布的查询中的 COUNT(*) 与 ExecuteScalar 可能是一个更好的解决方案。
关于c# - MySql.Data.MySqlClient C# 控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980162/