C#将字符串变量内的转义字符转换为SQL查询的字符串文字

时间:2015-08-06 14:16:28

标签: c# sql-server regex string string-literals

我正在尝试将包含转义字符(如“\ r \ n”)的C#中的字符串变量转换为字符串文字,以便可以在SQL查询中使用它。

// Here is the value of the string which IS NOT actually a verbatim string literal, but a value passed on from a selected dropdown list.
strEmailText = "We're writing in regard to XXX mentioned above.\r\nPlease contact us.\r\nWe're available by direct reply.\r\nThank you for your assistance."

// Here I create the actual SQL string for use to query the database
strSQL = @"SELECT DISTINCT TBL_EmailText.ID FROM TBL_EmailText WHERE (TBL_EmailText.Text = N'" + strEmailText + "')";

现在,每当我尝试使用此SQL字符串进行搜索时,它都会转换转义字符,并像这样混淆查询:

@"SELECT DISTINCT TBL_EmailText.ID FROM TBL_EmailText WHERE (TBL_EmailText.Text = N'We''re writing in regard to XXX mentioned above.

Please contact us.

We''re available by direct reply.

Thank you for your assistance.')"

所以我的问题是,我怎样才能使其工作,以便使用以下内容进行搜索:

@"SELECT DISTINCT TBL_EmailText.ID FROM TBL_EmailText WHERE (TBL_EmailText.Text = N'We''re writing in regard to XXX mentioned above.\r\nPlease contact us.\r\nWe''re available by direct reply.\r\nThank you for your assistance.')"

我找到并尝试使用此代码,但它不起作用:

protected internal static StringWriter ToLiteral(string strString)
    {
        using (StringWriter strWriter = new StringWriter())
        {
            using (CodeDomProvider cdpProvider = CodeDomProvider.CreateProvider("CSharp"))
            {
                cdpProvider.GenerateCodeFromExpression(new CodePrimitiveExpression(strString), strWriter, null);
                return strWriter.ToString();
            }
        }
    }

它仍会转换转义字符。

任何帮助将不胜感激。提前谢谢!

3 个答案:

答案 0 :(得分:3)

你不应该生成嵌入了文字字符串的SQL句子,这就是query parameters的用途。

答案 1 :(得分:2)

使用字符串文字:

strEmailText = @"We're writing in regard to XXX mentioned above.\r\nPlease contact us.\r\nWe're available by direct reply.\r\nThank you for your assistance."

另外,在sql中使用参数以确保正确插入,并防止sql注入。

答案 2 :(得分:1)

您的问题不是由转义的字符引起的。那些只与C#有关。当字符串连接到您的SQL查询时,它们将只是常规回车和换行。

真正的问题是首先使用字符串连接引起的!您的数据中有一个撇号,一旦连接就会弄乱最终查询。

相反,使用参数化查询,这不会是一个问题,你也将避免SQL注入漏洞!

// Here is the value of the string which IS NOT actually a verbatim string literal, but a value passed on from a selected dropdown list.
strEmailText = "We're writing in regard to XXX mentioned above.\r\nPlease contact us.\r\nWe're available by direct reply.\r\nThank you for your assistance."

// Here I create the actual SQL string for use to query the database
strSQL = @"SELECT DISTINCT TBL_EmailText.ID FROM TBL_EmailText WHERE TBL_EmailText.Text = @EmailText";

using (var sqlCmd = new SqlCommand(strSQL, conn))
{
    sqlCmd.CommandType = CommandType.Text;
    sqlCmd.Parameters.Add(new SqlParameter { ParameterName = "@EmailText", SqlDbType = SqlDbType.NVarChar, Value = strEmailText });

    using(SqlDataReader rdr = sqlCmd.ExecuteReader())
    {
        //Do something with the data
    }
}

请注意在sql查询中使用参数@EmailText以及如何将其添加到Parameters对象的sqlCmd集合中。

这种方法将消除查询中的撇号问题,更重要的是消除sql注入漏洞。

相关问题