Search code examples
c#sql-updateoledb

How can i use update statements in c# correctly


This is my update statement that cosntains a syntax error, please can anyonje point out the error to me im having a real struggle, my knowlede isnt the best.

Updated but sti;ll having errors.

string sql = $"UPDATE Appointments SET AppDate = {dtpDate.Value.ToShortDateString()}, ContactName = {txtCustomer.Text}, ContactNumber = {txtNumber}, Comment = {txtComment} WHERE ID = {AppID}";
                String contactNo = txtNumber.Text.ToString();
                String comment = txtComment.Text.ToString();
                string date1 = dtpDate.Value.ToString("dd/M/yyyy");
                


                string sql = $"UPDATE Appointments SET AppDate = @Date1, ContactName = @Customer, ContactNumber = @ContactNo, Comment = @Comment WHERE ID = @AppID";

                SqlParameter param = new SqlParameter();
                param.ParameterName = "@Date1";
                param.Value = date1;
                param.ParameterName = "@Customer";
                param.Value = customer;
                param.ParameterName = "@ContactNo";
                param.Value = contactNo;
                param.ParameterName = "@Comment";
                param.Value = comment;
                param.ParameterName = "@AppID";
                param.Value = AppID;```

Solution

  • Asuming datatype of ContactName, ContactNumber and Comments as VARCHAR, dtpDate.Value as Date and ID to be of type int, Your query needs to be have a syntax like this:

    string sql = $"UPDATE Appointments SET AppDate = '{dtpDate.Value.ToString("yyyy-MM-dd")}', ContactName = '{txtCustomer.Text}', ContactNumber = '{txtNumber}', Comment = '{txtComment}' WHERE ID = {AppID}";
    

    During concatenation in C#, you need to make sure that string values are enclosed in single quotes.