MySQL C#验证错误

use*_*388 -4 c# mysql passwords validation username

public void Find(string userName, string password)
    {
        string query = "SELECT COUNT(*) FROM user WHERE username =\'" + userName + "\', \'" + GetMd5Sum(password) + "\'";
        MySqlCommand cmd = new MySqlCommand(query, connection);

        try
        {

            //This will return 1 if the username and password exist.
            //It will return 0 if the username and password are not found.
            int count = (int)cmd.ExecuteScalar();

            if (count > 0)
                MessageBox.Show("You have succesfully logged in!");
            else
                MessageBox.Show("Incorrect username or password.");

            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
    }
Run Code Online (Sandbox Code Playgroud)

我认为这就是问题所在.任何人都可以解释或帮助我解决这个错误吗?

错误是:

您的SQL语法有错误; 查看与您的MySQL服务器版本对应的手册,以便在第1行的"C8059E2Ec7419F590E79D7F1B774BFE6"附近使用正确的语法

Jon*_*eet 5

你的SQL看起来像这样(当然是值$user$passwordhash值):

SELECT COUNT(*) FROM user WHERE username = '$user', '$passwordhash'
Run Code Online (Sandbox Code Playgroud)

你期望第二个值做什么?我怀疑你想要的东西:

SELECT COUNT(*) FROM user WHERE username = '$user' AND passhash = '$passwordhash'
Run Code Online (Sandbox Code Playgroud)

(passhash根据您的实际列名进行更改.)

然而,你应该只是添加文本到你的查询.相反,更改代码以使用参数化SQL来避免SQL注入攻击.始终使用参数而不是直接在SQL中包含值:

  • 它避免了SQL注入攻击
  • 它避免了不必要且容易出错的字符串转换(特别是对于日期/时间值)
  • 它使您的代码(SQL)与您的数据分开,使查询更容易阅读