C#-更新按钮单击
作者:互联网
我有一个按钮,代码还可以,但是更新时出现错误.
这是代码:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set cDetails = " + lblcDetails.Text + ", cDetails2 = '" + lblcDetails2.Text + "', PhoneNumber = '" + lblPhoneNumber.Text + "', PersonCharge = '" + lblPersonInCharge.Text + "' Where cName = '" + lblcNameP.Text + "'";
cmdC.ExecuteNonQuery();
MessageBox.Show("Data Updated");
}
这是错误.
链接到大图的错误:Error Picture
表格如下:
在我眼中,错误可能是文本框中的空格..但我不知道是否是.
谁能指出我做错了什么?
解决方法:
请不要在sql命令中使用字符串连接.您可能会缺少一些引号,很难找到它的位置.使用parameterized queries
.
同样,这种级联也可用于SQL Injection
攻击.
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set cDetails = @cDetails , cDetails2 = @cDetails2, PhoneNumber = @PhoneNumber, PersonCharge = @PersonCharge Where cName = @cName";
cmdC.Parameters.AddWithValue("@cDetails", lblcDetails.Text);
cmdC.Parameters.AddWithValue("@cDetails2", lblcDetails2.Text);
cmdC.Parameters.AddWithValue("@PhoneNumber", lblPhoneNumber.Text);
cmdC.Parameters.AddWithValue("@PersonCharge ", lblPersonInCharge.Text);
cmdC.Parameters.AddWithValue("@cName", lblcDetails.Text);
cmdC.ExecuteNonQuery();
标签:button,sql-update,sql,c,winforms 来源: https://codeday.me/bug/20191122/2058711.html