Skip to main content
Continuum Concepts

Escape MySQL Queries in .NET (C#)

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.