简体   繁体   English

C#和SQL的新功能-为什么我的.AddWithValue不起作用?

[英]New to C# and SQL - Why does my .AddWithValue not work?

So currently I have this: 所以目前我有这个:

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);
            }
        }
}

Now here is the issue, I don't get a compiler error when I run this, yet the sql.Parameters.AddWithValue( .. ); 现在是问题所在,运行此命令时没有出现编译器错误,但是sql.Parameters.AddWithValue(..); part doesn't actually add the string 'username' to the sql query. 部分实际上并未将字符串“ username”添加到sql查询中。 It simply leaves it at @username. 它只是将其保留在@username。 Does anyone know what I am doing wrong here? 有人知道我在这里做错了吗?

You forgot to call .Prepare() . 您忘记了调用.Prepare()

MySqlCommand sql = new MySqlCommand("SELECT salts FROM users WHERE usernames = @username;", connection);
sql.Prepare(); // You forgot this *********************
sql.Parameters.AddWithValue("@username", username);

Below is an example using the proper resources with a using block: 下面是使用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();
    }
}

Tweak yours accordingly to clean up the resources automatically for you. 相应地调整您的资源,以自动为您清理资源。 MSDN shows examples of all of this. MSDN展示了所有这些示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM