更新语句中的错误

时间:2014-03-28 19:10:40

标签: c# asp.net sql-server

这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
{

   SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString());

   con.Open();

   SqlCommand com = new SqlCommand("update slab set salbn = @salbn,basic = @basic,hra = @hra,trvl = @trvl,mdeca = @mdeca,atnd = @atnd,tote = @tote where salbn =" + DropDownList1.SelectedItem.Text, con);

   com.Parameters.AddWithValue("@salbn", TextBox21.Text);
   com.Parameters.AddWithValue("@basic", TextBox12.Text);
   com.Parameters.AddWithValue("@hra", TextBox13.Text);
   com.Parameters.AddWithValue("@trvl", TextBox15.Text);
   com.Parameters.AddWithValue("@mdeca", TextBox16.Text);
   com.Parameters.AddWithValue("@atnd", TextBox18.Text);
   com.Parameters.AddWithValue("@tote", TextBox20.Text);

   com.ExecuteNonQuery();

   con.Close();

   MsgBox("Updated Successfully");

}

我收到了一个错误: “列名'Group_A'无效。” 我的查询就是这样 “update slab set salbn = @ salbn,basic = @ basic,hra = @ hra,trvl = @ trvl,mdeca = @ mdeca,atnd = @ atnd,tote = @tote where salbn = Group_A”

这里Group_A是DropDownList1.SelectedItem.Text。我使用的是asp.net/C#,sql server2008。

1 个答案:

答案 0 :(得分:4)

该值必须采用单引号。

SqlCommand com = new SqlCommand("update slab set salbn = @salbn,basic = @basic,hra = @hra,trvl = @trvl,mdeca = @mdeca,atnd = @atnd,tote = @tote where salbn ='" + DropDownList1.SelectedItem.Text + "'", con);

话虽如此,您确实应该在WHERE子句中使用参数化SQL,就像您在其他地方使用的那样,以防止SQL注入攻击。

SqlCommand com = new SqlCommand("update slab set salbn = @salbn,basic = @basic,hra = @hra,trvl = @trvl,mdeca = @mdeca,atnd = @atnd,tote = @tote where salbn = @param", con);
com.Parameters.AddWithValue( "@param", DropDownList1.SelectedItem.Text );