我在UPDATE
语句中遇到问题我正在尝试通过WHERE
子句更新表数据,这使我错误地发现数据未匹配。
sqL = "UPDATE Customer SET name= '" & txtName.Text & "', adress= '" & txtAdress.Text & "', contact = '" & txtContact.Text & "' WHERE Customer_ID = '" & txtCustomerID.Text & "'"
我也试过
sqL = "UPDATE Customer SET name= '" & txtName.Text & "', adress= '" & txtAdress.Text & "', contact = '" & txtContact.Text & "' WHERE Customer_ID = '" & Convert.ToInt32(txtCustomerID.Text) & "'"
没有运气。
答案 0 :(得分:2)
请使用更清晰,更安全的参数化查询:
如果你在c#:
string sql = "UPDATE Customer SET name= @name, adress=@address, contact = @contact" +
" WHERE Customer_ID = @id";
using(SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@name",txtName.Text);
cmd.Parameters.AddWithValue("@address",txtAdress.Text);
cmd.Parameters.AddWithValue("@contact",txtContact.Text);
/*
NOTE: Make sure Textbox value is convertible to Customer_ID data type
before executing the query. It should be done before the using statement.
Use string.Trim() method to remove any space characters at start/end
*/
cmd.Parameters.AddWithValue("@id",txtCustomerID.Text.Trim());
conn.Open();
cmd.ExecuteNonQuery();
}
答案 1 :(得分:0)
看起来Customer_ID的数据类型是int。在这种情况下,请从转换语句周围删除单引号。
sqL = "UPDATE Customer SET name= '" & txtName.Text & "', adress= '" & txtAdress.Text & "', contact = '" & txtContact.Text & "' WHERE Customer_ID = " & Convert.ToInt32(txtCustomerID.Text)
但请仔细检查表格中的数据类型。
答案 2 :(得分:0)
您的查询无法编译: -
C#中的字符串连接运算符是加号而不是&符号。
但是,kaf
建议始终使用参数化查询。
尝试使用加号代替&符号。
"UPDATE Customer SET name= '" + txtName.Text + "', adress= '" + txtAdress.Text + "', contact = '" + txtContact.Text + "' WHERE Customer_ID = '" + txtCustomerID.Text + "'"
如果客户ID为int,则将其转换为int。