更新语句出错

本文关键字:出错 语句 更新 | 更新日期: 2023-09-27 17:54:30

下面是我的代码:

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, atand = @atnd,tote = @tote where salbn = Group_A"

这里Group_A是dropdownlist1 . selecteitem . text。我使用asp.net/C#, sql server2008.

更新语句出错

需要用单引号括起来

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 );