System.Data.SqlClient.SqlException报错求助:'Judgment'附近语法不正确
解决SQL语法错误及SQL注入风险的方案
嘿,这个问题我之前也踩过坑,咱们来一步步拆解问题根源和解决办法:
首先,你遇到的'Judgment'附近有语法错误,核心原因是直接把用户输入拼接进SQL语句。举个例子:如果某个字段(比如Description)的输入内容是Judgment's story,拼接后的SQL会变成Description='Judgment's story'——这里的单引号会提前闭合字符串,后面的s story'就成了无效的SQL语法,自然触发错误。而且这种写法还存在极高的SQL注入风险,恶意用户能通过构造输入直接篡改你的数据库。
正确的解决方案:使用参数化查询
参数化查询会自动处理特殊字符,彻底避免语法错误和SQL注入,这也是数据库交互的行业最佳实践。修改后的代码如下:
protected void gvComic_RowUpdating(object sender, GridViewUpdateEventArgs e) { int ID = Convert.ToInt32(gvComic.DataKeys[e.RowIndex].Value.ToString()); string Name = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[1].Controls[0])).Text; string UnitPrice = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[2].Controls[0])).Text; string PublishCountry = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[3].Controls[0])).Text; string Author = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[4].Controls[0])).Text; string Description = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[5].Controls[0])).Text; string Translator = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[6].Controls[0])).Text; string CoverPage = ((TextBox)(gvComic.Rows[e.RowIndex].Cells[7].Controls[0])).Text; using (SqlConnection conn = new SqlConnection(cs)) { conn.Open(); // 用占位符代替直接拼接的内容 string sql = @"UPDATE Comics SET Name=@Name, UnitPrice=@UnitPrice, PublishCountry=@PublishCountry, Author=@Author, Description=@Description, Translator=@Translator, CoverFile=@CoverFile WHERE CId=@ID"; SqlCommand cmd = new SqlCommand(sql, conn); // 逐个添加参数,数据库会自动处理特殊字符和类型匹配 cmd.Parameters.AddWithValue("@ID", ID); cmd.Parameters.AddWithValue("@Name", Name); cmd.Parameters.AddWithValue("@UnitPrice", UnitPrice); cmd.Parameters.AddWithValue("@PublishCountry", PublishCountry); cmd.Parameters.AddWithValue("@Author", Author); cmd.Parameters.AddWithValue("@Description", Description); cmd.Parameters.AddWithValue("@Translator", Translator); cmd.Parameters.AddWithValue("@CoverFile", CoverPage); int t = cmd.ExecuteNonQuery(); if (t > 0 ) { Response.Write("<script>alert('Data has updated!')</script>"); gvComic.EditIndex = -1; BindGrind(); } } }
额外补充细节:
- 原来的代码里
WHERE CId='" + ID + "'把整数ID用单引号包裹,这会让数据库做不必要的类型转换,参数化后直接传入int类型更高效也更严谨; - 如果
UnitPrice是数值类型(比如decimal),建议先把输入的字符串转换为对应数值类型再传入参数,避免潜在的类型错误; - 永远不要信任任何用户输入,参数化是规避数据库安全风险的基础操作。
内容的提问来源于stack exchange,提问作者ZhongHua Wong
相关产品推荐
相关产品推荐

