# Sunday, March 29, 2009
« Windows 7 Build 7057 on my Dell Inspiron... | Main | Edit Text in a .NET Assembly »
This page tells you how to do it in PHP, and it also tells you what characters need to be escaped. So, converting it to C# was not that hard:
public static string MySqlEscape(this string usString)
{
    if (usString == null)
    {
        return null;
    }
    // SQL Encoding for MySQL Recommended here:
    // http://au.php.net/manual/en/function.mysql-real-escape-string.php
    // it escapes \r, \n, \x00, \x1a, baskslash, single quotes, and double quotes     return Regex.Replace(usString, @"[\r\n\x00\x1a\\'""]", @"\$0");
}
I use it in a static class as an extension method. If you don't speak Regex, what it says is this:
"If you find any of the following list of characters: \r, \n \x00, \x1a, \, ', ", replace them with a backslash followed by themselves."

This will put a backslash before any of the offending characters and make your query safe from SQL Injection. Please don't take my word for it though. If you use it, test it thoroughly.

Sunday, March 29, 2009 5:14:56 PM (Central Standard Time, UTC-06:00)
Tuesday, November 03, 2009 9:59:29 PM (Central Standard Time, UTC-06:00)
This can be accomplished using the MySqlHelper class in the MySql C# client library. i.e. string escapedData = MySqlHelper.EscapeString(data);
All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview