Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to escape characters in a DataTable Filter Expression

Tags:

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)) 

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.

like image 988
Ady Avatar asked Dec 22 '08 12:12

Ady


People also ask

How do you escape characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.

How do you escape a character in a string?

\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .

What is meant by escaping characters?

In computing and telecommunication, an escape character is a character that invokes an alternative interpretation on the following characters in a character sequence. An escape character is a particular case of metacharacters.

How do you escape special characters in node?

“js escape special characters” Code Answer's Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes, and ampersands. Place backslash before the characters to make it display.


2 Answers

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

like image 151
Rory Avatar answered Sep 22 '22 07:09

Rory


If I replace ' with two single ' the query works.

like image 20
Ady Avatar answered Sep 18 '22 07:09

Ady