即使我输入了正确的用户凭据,也会显示无效的用户凭据。我不知道我的参数是否错误或者我的查询是否错误。我想了解参数化查询,但我不知道我在这里做错了什么。
con.OpenConnection();
using (con.connection)
{
String query = "SELECT * FROM tblUser WHERE Username = @Username and Password = @Password";
try
{
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.Add("@Username", MySqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("@Password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
MessageBox.Show("Invalid user credentials.");
}
else
{
//Do stuff
}
}
catch (MySqlException mse)
{
MessageBox.Show(mse.Message);
}
finally
{
con.CloseConnection();
}
答案 0 :(得分:0)
不确定为什么它不起作用但是如果你使用AddWithValue,它会起作用。像这样的东西
cmd.Parameters.AddWithValue("@Username", txtUsername.Text);
cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
答案 1 :(得分:0)
更改代码以便它调用方法,当您单击Button时,将Username和Password变量传递给此方法。在类级别为UserName和Password创建一个AutoProperty
private DataTable PopulateSomeDatatSet(DataSet aDataset, string UserName, string Password)
{
var query = "SELECT * FROM tblUser WHERE Username = @Username and Password = @Password";
MySqlDataAdapter sda;
using (SqlConnection connStr = new SqlConnection(ConnString)) //replace with your ConnectionString Variable
{
using (MySqlCommand cmd = new MySqlCommand(query, connStr))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Username", MySqlDbType.VarChar).Value = UserName;
cmd.Parameters.Add("@Password", MySqlDbType.VarChar).Value = Password;
sda = new MySqlDataAdapter(cmd);
new MySqlDataAdapter(cmd).Fill(aDataset);
}
}
((IDisposable)sda).Dispose();
return aDataset.Tables[0];
}