Search code examples
c#sqlsqlparameter

SQL parameters not working


This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:

private void btnAdd_Click(object sender, EventArgs e)
{
    string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
                       Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
    string query =
       "INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (@barcodeValue, @nameValue, @dateValue, @quantityValue, @priceValue) ;";
    SqlConnection conDataBase = new SqlConnection(constring);
    conDataBase.Open();
    using (var cmd = new SqlCommand(query, conDataBase))        
    {
        cmd.Parameters.AddWithValue("@barcodeValue", tbxBar.Text);
        cmd.Parameters.AddWithValue("@nameValue", tbxName.Text);
        cmd.Parameters.AddWithValue("@dateValue", dateDate.Value.Date);
        cmd.Parameters.AddWithValue("@quantityeValue", tbxQua.Text);
        cmd.Parameters.AddWithValue("@priceValue", tbxPrice.Text);
    }   
    conDataBase.Close();
}

The code might just be wrongly build or I could be missing some part I'm not sure.

I figured out what was not working, was the connection string. So opening a new question for that.

What i had to do is to open the connection and then execute the command


Solution

  • You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:

    using (var cmd = new SqlCommand(query, conDataBase))        
    {
        // set parameters...
    
        cmd.ExecuteNonQuery();
    }