【问题标题】:Handling special character input for data selection [duplicate]处理数据选择的特殊字符输入[重复]
【发布时间】:2012-11-15 07:06:34
【问题描述】:

更新

当'\'为转义助手%[]_时,后面四个字符需要转义

  1. http://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx - 喜欢
  2. Escape a string in SQL Server so that it is safe to use in LIKE expression
  3. How do I escape _ in SQL Server?

问题

虽然我搜索了很多,但在堆栈溢出中我找不到与以下完全匹配的问题。

我有一个名为 Log_Description 的数据库列。它有两条记录。

1)“样本百分比值记录”

2) “样品免费记录”

我正在使用SQL命令并设置参数如下所示

commandText = commandText + “Log_Description LIKE @Log_Description”;
command.Parameters.AddwithValue(“@Log_Description”, “%”+obj. LogDescription+”%”); 

假设用户输入“%”作为 txtLogDescription 文本框的搜索参数,我只需要显示第一条记录。但目前它正在显示这两个记录。

  1. 有哪些可能的方法来克服这个问题?
  2. 还有哪些其他字符可能会导致上述代码出现此类问题?

注意:我无法阻止用户输入“%”作为输入

注意:我使用 SQL Server 作为数据库

编辑

我现在使用的解决方案是Escaping the escape character does not work – SQL LIKE Operator

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

LINQ 方法(性能受到影响)如下

        Collection<Log> resultLogs = null;


        if (!String.IsNullOrEmpty(logSearch.LogDescription))
        {
            resultLogs = new Collection<Log>();
            var results = from o in logs where o.LogDescription.Contains(logSearch.LogDescription) select o;
            if (results != null)
            {
                foreach (var log in results)
                {
                    resultLogs.Add((Log) log);
                }
            }
        }
        else
        {
            resultLogs = logs;
        }

【问题讨论】:

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


【解决方案1】:

至于转义 %,请参阅 Tommy Grovnes 对该问题的评论。

如果您可以使用List&lt;T&gt; 代替Collection&lt;T&gt;(请参阅here),则可以更简洁地编写:

var descr = logSearch.logDescription;
var results = (
    from o in logs
    where String.IsNullOrEmpty(descr) ||
            o.LogDescription.Contains(descr)
    select o
).ToList();

如果您仍然需要Collection&lt;T&gt;,您可以将 LINQ 查询的结果包装在 Collection 构造函数中:

var results = new Collection<Log>((
    from o in logs
    where String.IsNullOrEmpty(descr) ||
            o.LogDescription.Contains(descr)
    select o
).ToList());

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多