单击按钮更新

时间:2013-12-31 08:54:45

标签: c# sql winforms button sql-update

我有一个按钮,代码没问题,但更新时出错。

这是代码:

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

链接到更大图片的错误:Error Picture

表单如下所示:

Form

现在在我的脑海里,错误可能是文本框中的空格..但我不知道是不是。

谁能指出我哪里做错了?

4 个答案:

答案 0 :(得分:3)

不要在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();

答案 1 :(得分:0)

更改初始catalog.put ypur表名称

conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=Datbasename;Integrated Security=True";

试试这个

cmd.Parameters.AddWithValue("@FirstDetail",textbox1.text);

cmd.Parameters.AddWithValue("@SecondDetail", Textbox2.Text);

refer here

答案 2 :(得分:0)

为了避免语法错误,请将格式化字符串用作

cmdC.CommandText =string.Format("Update ComDet set cDetails = '{0}',cDetails2 ='{1}',PhoneNumber = '{2}',PersonCharge = '{3}' Where cName = '{4}'", lblcDetails.Text, lblcDetails2.Text , lblPhoneNumber.Text , lblPersonInCharge.Text , lblcNameP.Text );

答案 3 :(得分:0)

我猜两件事情都不正确:

在数据源上,初始目录引用数据库的名称。你有“主人”。应该像:

conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=yourDBname;Integrated Security=True";

此外,您在SQL语句中缺少引号(并且它们的顺序并不总是正确),它应该是:

cmdC.CommandText = "Update ComDet set cDetails = '" + lblcDetails.Text + "', cDetails2 = '" + lblcDetails2.Text + "', PhoneNumber = '" + lblPhoneNumber.Text + "', PersonCharge = '" + lblPersonInCharge.Text + "' Where cName = '" + lblcNameP.Text + "'";