本文介绍了正确的方式来逃避在数据表中筛选前pression字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个函数来正确地逃避字符串文字的过滤器EX pressions。例如:

I would like to know if there is a function to correctly escape string literals for filter expressions. e.g.:

DataTable.Select(String.Format("[name] = '{0}'", MyName))

如果MYNAME包含'或生成异常的一些其他重要特征。 表明,这些字数应该是正确的微软文档逃过一劫,但对于如何这个有点混乱是必须要做的。

If MyName contains ' or a number of other key characters an exception is generated. The Microsoft documentation indicates that these charaters should be correctly escaped, however there is a bit of confusion on how this is to be done.

我已经试过与\'替换,也[']如文档中表示,但查询仍然失败。

I have tried replacing ' with \' and also ['] as indicated in the documentation, however the query still fails.

非常感谢

推荐答案

通过它增加一倍,达到'逃逸的单引号。逃生*%[]字符包裹在[]。例如

Escape the single quote ' by doubling it to ''. Escape * % [ ] characters by wrapping in []. e.g.

private string EscapeLikeValue(string value)
{
    StringBuilder sb = new StringBuilder(value.Length);
    for (int i = 0; i < value.Length; i++)
    {
        char c = value[i];
        switch (c)
        {
            case ']':
            case '[':
            case '%':
            case '*':
                sb.Append("[").Append(c).Append("]");
                break;
            case '\'':
                sb.Append("''");
                break;
            default:
                sb.Append(c);
                break;
        }
    }
    return sb.ToString();
}

public DataRow[] SearchTheDataTable(string searchText)
{ 
     return myDataTable.Select("someColumn LIKE '" 
                                 + EscapeLikeValue(searchText) + "'");
} 

由于这里 例子

Thanks to examples here

这篇关于正确的方式来逃避在数据表中筛选前pression字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!