所以目前我有这个:
private void button1_Click(object sender, EventArgs e) {
string username = txtboxUsername.Text;
string password = txtboxPassword.Text;
string salt = string.Empty;
connection.Open();
MySqlCommand sql = new MySqlCommand("SELECT salts FROM users WHERE usernames = @username;", connection);
sql.Parameters.AddWithValue("@username", username);
using (MySqlDataReader reader = sql.ExecuteReader()) {
if (reader.HasRows) {
reader.Read();
salt = reader.GetString(0);
} else {
MessageBox.Show(sql.CommandText);
}
}
}
现在这是问题,我运行时没有出现编译器错误,但是sql.Parameters.AddWithValue(..); part实际上并没有将字符串'username'添加到sql查询中。它只是将它留在@username。有谁知道我在这里做错了什么?
答案 0 :(得分:1)
您忘了拨打.Prepare()
。
MySqlCommand sql = new MySqlCommand("SELECT salts FROM users WHERE usernames = @username;", connection);
sql.Prepare(); // You forgot this *********************
sql.Parameters.AddWithValue("@username", username);
以下是使用using
块的适当资源的示例:
using (MySqlConnection lconn = new MySqlConnection(connString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = "update " + activeTblName + " set bn=@bn where qId=@qId";
cmd.Prepare();
cmd.Parameters.AddWithValue("@qId", pqId);
cmd.Parameters.AddWithValue("@bn", ptheValue);
cmd.ExecuteNonQuery();
}
}
相应调整您的内容,自动为您清理资源。 MSDN显示了所有这些的例子。