使用更新查询时,“8”错误附近的语法不正确

时间:2011-05-18 10:26:30

标签: asp.net sql database sql-update

 static public void updateSelectedCaravan(string make, string model, string birth, string year, string Int, string ext, string width, string Unladen, string mtplm, string warranty, string freeText, string price, string location, string Tel, string Email, int makeID, string description)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    conn.Open();
    SqlCommand updateNews = new SqlCommand("Update [productDetail] SET [make] =@make , [model] = @model , [Berth] = @birth , [Year] =  @year , [InternalLength] = @Int , [ExternalLength] = @ext, [Width] = @width , [UnladenWeight] = @Unladen , [MTPLM] = @mtplm , [Warranty] = @warranty , [FreeTextDetails] = @freeText , [Price] = @price , [Location] = @location , [Tel] = @Tel , [Email] = @Email , [description] = @description where [makeID] = @makeID", conn);
    updateNews.Parameters.AddWithValue("@make", make);
    updateNews.Parameters.AddWithValue("@model", model);
    updateNews.Parameters.AddWithValue("@birth", birth );
    updateNews.Parameters.AddWithValue("@year", year);
    updateNews.Parameters.AddWithValue("@Int", Int);
    updateNews.Parameters.AddWithValue("@ext", ext);
    updateNews.Parameters.AddWithValue("@width", width);
    updateNews.Parameters.AddWithValue("@Unladen", Unladen);
    updateNews.Parameters.AddWithValue("@mtplm", mtplm);
    updateNews.Parameters.AddWithValue("@warranty",warranty);
    updateNews.Parameters.AddWithValue("@freeText", freeText);
    updateNews.Parameters.AddWithValue("@price", price);
    updateNews.Parameters.AddWithValue("@location", location);
    updateNews.Parameters.AddWithValue("@Tel", Tel);
    updateNews.Parameters.AddWithValue("@Email",Email );
    updateNews.Parameters.AddWithValue("@description",description );
    updateNews.Parameters.AddWithValue("@makeID", makeID);
    updateNews.ExecuteNonQuery();
    conn.Close();
}

上面的查询不起作用它给出了错误'8'附近的语法不正确,它之前工作正常,但我不知道它停止工作的原因,我调试了d查询并传递了所有必需的值。

4 个答案:

答案 0 :(得分:2)

您的一个数据项包含单引号,可能在数字8旁边。这会破坏您的SQL,并且是您应该防范的意外SQL Injection的示例。

您应该使用参数化查询。这样,单引号将自动为您转义,此问题将消失。

答案 1 :(得分:1)

停止创建自己的SQL查询。它容易受到SQL注入攻击。改为使用参数化表达式,您将不再需要处理这些参数错误。

 SqlCommand cmd = new SqlCommand("UPDATE productDetail SET make = @make WHERE id = @id");
 cmd.Parameters.AddWithValue("@make", "someValue");
 cmd.Parameters.AddWithValue("@id", 1234);

 // execute

答案 2 :(得分:1)

首先,您应该对您的查询进行简化,因为如果有人恶意将您的系统用于SQL注入,那么您在此处存在巨大的安全问题。

其次,这些领域是什么类型的?如果它们是int,就像它们中的很多应该是,你不需要这样做:

SET year = '2011'

你会这样做:

SET year = 2011

这不会引发错误,但建议使用。

调试查询的最佳方法是在执行查询之前打印查询,以查看实际构建的查询是什么。正如其他人提到的那样,它可能是一个导致问题的单引号。

如果您对查询进行了简化,那么它将起作用,并且会更安全。

答案 3 :(得分:1)

除上述答案外,我还建议您尝试在函数中发送类对象。

这意味着您应该有一个对象模型项目。这包含您在函数中传递的所有参数的类。

将此项目的引用添加到您的数据层/表示中,并从演示文稿中发送此类的对象,该对象填充了数据成员值以访问成员数据。这样,如果明天你必须增加/减少参数,那么你不需要改变功能签名。

相关问题