Escaping backslash character in C# .NET MySQL-queries
Using escape-sequences like \t or \n is one thing, but escaping the escapecharacter (often ‘\’) can sometimes be a pain in the A*S*S… This is especially true when the string you’re escaping is about to be processed by several succeeding processes, like: 1) a compiler, 2) a regex-engine, 3) a database, … , etc.
Anyways, I’ve experimented some with MySql-queries from within C# .NET, using Windows paths (containing backslashes as path separators) in the WHERE-clauses. We have a query of one of the forms:
case 1: = operator
querystring1 = "SELECT a,b,path FROM table " + "WHERE path = '" + patharg1 + "';";
or
case 2: LIKE operator
querystring2 = "SELECT a,b,path FROM table " + "WHERE path LIKE '" + patharg2 + "';";
Here is what I’ve found out:
case 1: = operator
Use 4 backslashes for each backslash in the saved record you’re matching against. You could do:
patharg1 =
patharg1.Replace("\\", "\\\\");
(The 2 backslashes in the first replace-argument is for escaping the backslash within the compiler.)
case 1: LIKE operator
Use 8(!) backslashes for each backslash in the saved record you’re matching against. You could do:
patharg2 =
patharg2.Replace("\\", "\\\\\\\\");
(The 2 backslashes in the first replace-argument is for escaping the backslash within the compiler.)
The two cases could then look like this:
case 1:
querystring1 = "SELECT a,b,path FROM table " + "WHERE path = 'c:\\\\some\\\\path.txt';";
case 2:
querystring2 = "SELECT a,b,path FROM table " + "WHERE path LIKE 'c:\\\\\\\\some\\\\\\\\path.txt';";
The above is if you put the querystring into, for instance, a MySqlCommand’s CommandText.
However, if you use datasets and run something like
dataTable.Select(filterExpression)
where dataTable is a DataTable instance and filterExpression is a string, you must not escape the backslash more than for a usual string (you’ll just write “\\” or @”\”, because some kind of escape of the backslash is always necessary for the compiler).
Tags: .NET, C#, escapecharacters, MySQL, programming
