3

我正在尝试获取帐户表的行数,以便我可以登录帐户,但 MySQL 参数没有添加这些值。

这是我的代码:

public int MyMethod(string username, string password)
{
    int count = 0;
    string query = "SELECT * FROM accounts WHERE username = '?user' AND password = '?pass' LIMIT 1;";

    using (MySqlCommand cmd = new MySqlCommand(query, connector))
    {
        cmd.Parameters.Add(new MySqlParameter("?user", username));
        cmd.Parameters.Add(new MySqlParameter("?pass", password));

        count = int.Parse(cmd.ExecuteScalar().ToString());
    }

    return count;
}
4

4 回答 4

4

参数占位符不应该用单引号括起来,因为它迫使它成为一个值而不是一个参数,试试这个,

public int MyMethod(string username, string password)
{
    int count = 0;
    string query = "SELECT * FROM accounts WHERE username = @user AND password = @pass LIMIT 1;";

    using (MySqlCommand cmd = new MySqlCommand(query, connector))
    {
        cmd.Parameters.Add(new MySqlParameter("@user", username));
        cmd.Parameters.Add(new MySqlParameter("@pass ", password));

        connector.Open(); // don't forget to open the connection
        count = int.Parse(cmd.ExecuteScalar().ToString());
    }

    return count;
}
于 2013-01-14T14:01:26.680 回答
1

我相信你想做这样的事情:

SELECT COUNT(*) FROM accounts WHERE username = '?user' AND password = '?pass';

这将为您提供具有指定用户名和密码的记录数。

于 2013-01-14T14:01:20.300 回答
1

尝试添加这样的参数:

cmd.Parameters.AddWithValue("@user", username);
cmd.Parameters.AddWithValue("@pass", password);
于 2013-01-14T14:21:57.060 回答
1

试试这个: @myVariable代替'?myVariable'SELECT COUNT(*)代替SELECT *

public int MyMethod(string username, string password)
{
  int count = 0;
  string query = "SELECT count(*) FROM accounts WHERE username = @user AND password = @pass LIMIT 1;";

   using (MySqlCommand cmd = new MySqlCommand(query, connector))
   {
      connector.Open(); 
      cmd.Parameters.AddWithValue("@user", username);
      cmd.Parameters.AddWithValue("@pass", password);       
      count = int.Parse(cmd.ExecuteScalar().ToString());
   }

   return count;
}
于 2013-01-14T15:13:28.290 回答