Search code examples
c#sql-serverdatabasecommandvariable-declaration

Must declare the scalar variable when updating my database


my code:

            SqlConnection con = new SqlConnection(@"DATA;");
            SqlDataAdapter cmd = new SqlDataAdapter();
            cmd.InsertCommand = new SqlCommand(" UPDATE TIME set TimeOut = @TimeOut Where TimeOut = @textBox1.Text", con);
            cmd.InsertCommand.Parameters.Add("@timeOut", DateTime.Now);
            con.Open();
            cmd.InsertCommand.ExecuteNonQuery();
            con.Close();

error: Must declare the scalar variable "@textBox1"

I tried declaring a variable with textBox1.Text but it didn't work

Solution

  • SqlConnection con = new SqlConnection(@"DATA;");
    SqlDataAdapter cmd = new SqlDataAdapter();
    cmd.InsertCommand = new SqlCommand(@"UPDATE `TIME` 
                                         SET TimeOut = @NewTimeOut 
                                         WHERE TimeOut = @OldTimeOut", con);
    cmd.InsertCommand.Parameters.Add("@NewTimeOut", DateTime.Now);
    cmd.InsertCommand.Parameters.Add("@OldTimeOut", DateTime.Parse(textBox1.Text));
    con.Open();
    cmd.InsertCommand.ExecuteNonQuery();
    con.Close();