如何修复SQL语法错误:'WHERE关键字附近语法不正确'
修复SQL UPDATE语句的语法错误及安全优化
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'WHERE'.'
语法错误原因及修复
你的SQL语句报错是因为**LastModified字段赋值语句末尾多了一个逗号**,这个多余的逗号破坏了SQL语法结构,导致WHERE子句无法被正确解析。
修复后的字符串拼接代码(仅解决语法问题,仍存在安全风险):
cmdUpdate.CommandText = "UPDATE Products2 " + " SET ProductName = '" + txtProductName.Text + "', " + " Description = '" + txtDescription.Text + "' , " + " Quantity = '" + txtQuantity.Text + "' , " + " CriticalLevel = '" + txtCriticalLevel.Text + "' , " + " PurchasePrice = '" + txtPurchasePrice.Text + "' , " + " SellingPrice = '" + txtSellingPrice.Text + "' , " + " ProductStatus = '" + cboStatus.Text + "' , " + " Created = '" + dtpCreated.Value.Date.ToString() + "' , " + " LastModified = '" + dtpLastModified.Value.Date.ToString() + "' " + // 移除此处的多余逗号 "WHERE (ProductNo=" + txtProdNo.Text + ");";
必做优化:替换为参数化查询
当前的字符串拼接写法存在致命的SQL注入风险,同时还可能因日期、数字等数据格式不匹配引发额外错误。推荐使用参数化查询,这是编写数据库操作代码的标准做法:
// 使用多行字符串提升可读性 cmdUpdate.CommandText = @"UPDATE Products2 SET ProductName = @ProductName, Description = @Description, Quantity = @Quantity, CriticalLevel = @CriticalLevel, PurchasePrice = @PurchasePrice, SellingPrice = @SellingPrice, ProductStatus = @ProductStatus, Created = @Created, LastModified = @LastModified WHERE ProductNo = @ProductNo;"; // 逐个添加参数,注意匹配数据库字段的类型 cmdUpdate.Parameters.AddWithValue("@ProductName", txtProductName.Text); cmdUpdate.Parameters.AddWithValue("@Description", txtDescription.Text); cmdUpdate.Parameters.AddWithValue("@Quantity", int.Parse(txtQuantity.Text)); // 假设Quantity是整数类型 cmdUpdate.Parameters.AddWithValue("@CriticalLevel", int.Parse(txtCriticalLevel.Text)); cmdUpdate.Parameters.AddWithValue("@PurchasePrice", decimal.Parse(txtPurchasePrice.Text)); // 价格建议用decimal类型 cmdUpdate.Parameters.AddWithValue("@SellingPrice", decimal.Parse(txtSellingPrice.Text)); cmdUpdate.Parameters.AddWithValue("@ProductStatus", cboStatus.Text); cmdUpdate.Parameters.AddWithValue("@Created", dtpCreated.Value.Date); cmdUpdate.Parameters.AddWithValue("@LastModified", dtpLastModified.Value.Date); cmdUpdate.Parameters.AddWithValue("@ProductNo", int.Parse(txtProdNo.Text)); // 假设ProductNo是整数类型
参数化查询的核心优势
- 彻底杜绝SQL注入攻击,保障数据安全
- 自动处理日期、数字等数据格式,避免格式转换错误
- 代码结构更清晰,便于维护和修改
内容的提问来源于stack exchange,提问作者Joseph Bernard Velasco
相关产品推荐
相关产品推荐

