如何在ADO.NET查询中加双引号?

时间:2009-09-08 04:51:42

标签: sql security ado.net sql-injection

我正在尝试阻止所有查询中的任何SQL注入,并且想知道如何在此查询中放置双引号。感谢

string.Format("SELECT TOP 10 article_guid, article_title 
               FROM article 
               WHERE article.article_isdeleted = 0 AND 
                     FREETEXT(article_title, @val)");

4 个答案:

答案 0 :(得分:4)

第1步:不要这样做。请改用parameterized query

参数化查询消除了与SQL注入攻击相关的大部分风险。

从链接:

private void CallPreparedCmd() {
    string sConnString = 
        "Server=(local);Database=Northwind;Integrated Security=True;";
    string sSQL = 
        "UPDATE Customers SET City=@sCity WHERE CustomerID=@sCustomerID";
    using (SqlConnection oCn = new SqlConnection(sConnString)) {
        using (SqlCommand oCmd = new SqlCommand(sSQL, oCn)) {
            oCmd.CommandType = CommandType.Text;

            oCmd.Parameters.Add("@sCustomerID", SqlDbType.NChar, 5);
            oCmd.Parameters.Add("@sCity", SqlDbType.NVarChar, 15);

            oCn.Open();
            oCmd.Prepare();

            oCmd.Parameters["@sCustomerID"].Value = "ALFKI";
            oCmd.Parameters["@sCity"].Value = "Berlin2";
            oCmd.ExecuteNonQuery();

            oCmd.Parameters["@sCustomerID"].Value = "CHOPS";
            oCmd.Parameters["@sCity"].Value = "Bern2";
            oCmd.ExecuteNonQuery();

            oCn.Close();
        }
    }
}

话虽如此,您可以通过转义双引号将引号插入字符串中:

string newstring = " \"I'm Quoted\" ";

答案 1 :(得分:2)

要防止SQL注入,您必须仅对所有查询使用SqlParameter个对象,如下所示:

SqlCommand  command = new SqlCommand("update tblFoo set x = @x");
SqlParamter param   = new SqlParameter("@x", SqlDbType.NVarChar);

param.Value = "hello\"";

command.Parameters.Add(param);

答案 2 :(得分:0)

为什么使用 string.Format ?您使用的是@parameterized查询,它是类型安全

Use Type-Safe SQL Parameters for Data Access

答案 3 :(得分:-1)

我不确定双引号是否会对你有所帮助(你可以通过逃避引用来添加它,如同在\“)。我过去所做的就是要注意单引号,所以在将@val包含在查询中之前,我对@val的内容进行了替换,如val.Replace("'", "''").