在DataTable过滤器表达式中转义字符的正确方法

时间:2008-12-22 12:17:08

标签: .net ado.net

我想知道是否有一个函数来正确转义过滤器表达式的字符串文字。 e.g:

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

如果MyName包含'或许多其他关键字符,则会生成异常。 Microsoft documentation表示应该正确转义这些字符,但是如何做到这一点会有一些混淆。

我已尝试将'with'和[']替换为文档中所示,但查询仍然失败。

非常感谢

3 个答案:

答案 0 :(得分:32)

通过将单引号加倍''来逃避单引号。通过包装在[]中转义*%[]个字符。 例如

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) + "'");
} 

感谢examples here

答案 1 :(得分:6)

如果我用'两个单'替换'查询有效。

答案 2 :(得分:0)

   /// <summary>
    /// <para>If a pattern in a LIKE clause contains any of these special characters * % [ ], those characters must be escaped in brackets [ ] like this [*], [%], [[] or []].</para>
    /// <para>If the pattern is not in a like clause then you can pass valueIsForLIKEcomparison = false to not escape brackets.</para>
    /// <para>Examples:</para>
    /// <para>- strFilter = "[Something] LIKE '%" + DataTableHelper.EscapeLikeValue(filterValue) + "%'";</para>
    /// <para></para>
    /// <para>http://www.csharp-examples.net/dataview-rowfilter/</para>
    /// </summary>
    /// <param name="filterValue">LIKE filterValue. This should not be the entire filter string... just the part that is being compared.</param>
    /// <param name="valueIsForLIKEcomparison">Whether or not the filterValue is being used in a LIKE comparison.</param>
    /// <returns></returns>
    public static string EscapeFilterValue(string filterValue, bool valueIsForLIKEcomparison = true)
    {
        string lb = "~~LeftBracket~~";
        string rb = "~~RightBracket~~";
        filterValue = filterValue.Replace("[", lb).Replace("]", rb).Replace("​*", "[*​]").Replace("%", "[%]").Replace("'", "''");
        if (valueIsForLIKEcomparison)
        {
            filterValue = filterValue.Replace(lb, "[").Replace(rb, "]");
        }
        else
        {
            filterValue = filterValue.Replace(lb, "[[]").Replace(rb, "[]]");
        }

        return filterValue;
    }