C# update语句中关键字“where”附近的语法不正确
我正在尝试更新数据,但它显示了一个错误C# update语句中关键字“where”附近的语法不正确,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我正在尝试更新数据,但它显示了一个错误 protected void Button2_Click(object sender, EventArgs e)//Update { { SqlConnection con = new SqlConnection(@"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True"); SqlCommand cmd = ne
protected void Button2_Click(object sender, EventArgs e)//Update
{
{
SqlConnection con = new SqlConnection(@"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE detail SET name='" + TxtBox_name.Text + "',address='" + TexBo_add.Text + "', WHERE contact_no='" + TexBo_num.Text + "'",con);
con.Open();
cmd.ExecuteNonQuery();
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('record updated');", true);
con.Close();
}
}
首先,这一切就像一套便宜的西装。第二,查看,以获取如何使用参数进行更新的示例。您需要删除where之前的逗号
但我建议您使用参数化查询
哦,在这么狭小的空间里犯了这么多错误: 实际的SQL错误只是一个不必要的逗号 但是:您有SQL注入问题 还有一个失踪的女孩 我非常喜欢使用工具来帮助避免疼痛。这是同样的使用整洁的
using(var con = new SqlConnection(ConnectionString))
{
con.Execute(@"update detail
set name=@name, address=@address
where contact_no = @num",
new {
name = TxtBox_name.Text,
address = TexBo_add.Text,
num = TexBo_num.Text
});
}
此外,还可能需要:
...
num = int.Parse(TexBo_num.Text)
...
但是,如果在同一方法中同时使用涉及UI控件和数据访问的代码,可能意味着您的UI代码做得太多了
using(var con = new SqlConnection(ConnectionString))
{
con.Execute(@"update detail
set name=@name, address=@address
where contact_no = @num",
new {
name = TxtBox_name.Text,
address = TexBo_add.Text,
num = TexBo_num.Text
});
}
...
num = int.Parse(TexBo_num.Text)
...