BlazeXenon
BlazeXenon

Reputation: 40

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( .. ); part doesn't actually add the string 'username' to the sql query. It simply leaves it at @username. Does anyone know what I am doing wrong here?

Upvotes: 0

Views: 1867

Answers (1)

Drew
Drew

Reputation: 24970

You forgot to call .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 (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.

Upvotes: 1

Related Questions