【问题标题】:Escaping the escape character does not work – SQL LIKE Operator转义转义字符不起作用 - SQL LIKE 运算符
【发布时间】:2012-12-13 13:37:23
【问题描述】:

我已将\ 用作escape character 用于LIKE 运算符。我正在转义以下四个字符

1 % 2 [ 3 ] 4 _

当我将转义字符作为输入传递时,查询不会返回值。我怎样才能让它发挥作用?

数据插入

DECLARE @Text VARCHAR(MAX)
SET @Text = 'Error \\\ \\  C:\toolbox\line 180'

INSERT INTO Account (AccountNumber,AccountType,Duration,ModifiedTime) 
VALUES (198,@Text,1,GETDATE())

代码

    static void Main(string[] args)
    {

        string searchValue1 = @"Error \\\ \\  C:\toolbox\line 180";
        string searchValue2 = @"55555";

        string result1 = DisplayTest(searchValue1);
        string result2 =  DisplayTest(searchValue2);

        Console.WriteLine("result1:: " + result1);
        Console.WriteLine("result2:: " + result2);
        Console.ReadLine();

    }}


     private static string DisplayTest(string searchValue)
    {
        searchValue = CustomFormat(searchValue);


        string test = String.Empty;
        string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string commandText = @"SELECT AccountType,* 
                              FROM Account 
                              WHERE AccountType LIKE @input ESCAPE '\'";
            using (SqlCommand command = new SqlCommand(commandText, connection))
            {
                command.CommandType = System.Data.CommandType.Text;
                command.Parameters.AddWithValue("@input", "%" + searchValue + "%");

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {

                            test = reader.GetString(0);
                        }
                    }
                }
            }
        }

        return test;
    }


    private static string CustomFormat(string input)
    {
        input = input.Replace(@"%", @"\%");
        input = input.Replace(@"[", @"\[");
        input = input.Replace(@"]", @"\]");
        input = input.Replace(@"_", @"\_");
        //input = input.Replace(@"\", @"\\");
        return input;
    }

参考:

  1. How can I escape square brackets in a LIKE clause?
  2. How to escape a string for use with the LIKE operator in SQL Server?

【问题讨论】:

  • 您是否考虑过在 C# 中使用不是特殊字符且不会自然出现在数据或搜索字符串中的转义字符?
  • 您的 SQL 语句与您提供的代码示例没有相似之处
  • @BenRobinson 我不明白你的意思。你能解释一下吗?
  • 自从我写这篇文章后,您已经更改了您的帖子,但我只是指出数据插入中的 SQL 与您的 DisplayTest 方法中的 SQL 完全不同。现在你试图用该代码解释的内容稍微清楚了。

标签: c# sql sql-server linq ado.net


【解决方案1】:

像这样修改CustomFormat 方法:

private static string CustomFormat(string input)
{
    input = input.Replace(@"\", @"\\"); 
    input = input.Replace(@"%", @"\%");
    input = input.Replace(@"[", @"\[");
    input = input.Replace(@"]", @"\]");
    input = input.Replace(@"_", @"\_");
    return input;
}

【讨论】:

  • 你可能还应该在其中添加input = input.Replace(@"'", @"\'");
  • input = input.Replace(@"'", @"''"); 是用单引号转义的正确方法。
  • 肯定转义单引号是最重要的吗?
  • 为什么要为 LIKE 运算符转义“'”字符?当然,整个值必须作为参数command.Parameters.AddWithValue 处理,其中应包括此转义。这种 LIKE 转义(CustomFormat)不是针对 SQL 注入的保护!
【解决方案2】:

用于 LIKE 处理的 C# 代码

     public static string WildcardFormatSpecialCharacter(string source)
    {
        string formattedResult = string.Empty;
        if (!String.IsNullOrEmpty(source))
        {
            //Escape the escape character
            formattedResult = source.Replace(DataLayerConstants.EscapeCharacter, DataLayerConstants.EscapeCharacterWithEscape);
            //The %
            formattedResult = formattedResult.Replace(DataLayerConstants.Percentage, DataLayerConstants.PercentageWithEscape);
            //The [
            formattedResult = formattedResult.Replace(DataLayerConstants.OpenSqaureBracket, DataLayerConstants.OpenSqaureBracketWithEscape);
            //The ]
            formattedResult = formattedResult.Replace(DataLayerConstants.CloseSqaureBracket, DataLayerConstants.CloseSqaureBracketWithEscape);
            //The _
            formattedResult = formattedResult.Replace(DataLayerConstants.Underscore, DataLayerConstants.UnderscoreWithEscape);
        }
        return formattedResult;
    }


    public const string EscapeCharacter = @"\";
    public const string EscapeCharacterWithEscape = @"\\";
    public const string Percentage = "%";
    public const string PercentageWithEscape = @"\%";
    public const string OpenSqaureBracket = "[";
    public const string OpenSqaureBracketWithEscape = @"\[";
    public const string CloseSqaureBracket = "]";
    public const string CloseSqaureBracketWithEscape = @"\]";
    public const string Underscore = "_";
    public const string UnderscoreWithEscape = @"\_";

其他要检查的事情Use of REPLACE in SQL Query for newline/ carriage return characters

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多