Click here to Skip to main content
13,201,763 members (72,801 online)
Click here to Skip to main content
Add your own
alternative version


1 bookmarked
Posted 25 Oct 2012

Equivalent function of mysql_real_escape_string() in C#

, 25 Oct 2012
Rate this:
Please Sign up or sign in to vote.
Implement function in C# to emulate functionality of mysql_real_escape_string() C API function.


Implement function in C# to emulate functionality of mysql_real_escape_string() C API function.


When writing application programs, any string that might contain any of these special characters must be properly escaped before the string is used as a data value in an SQL statement that is sent to the MySQL server.

MySQL Reference: Special Character Escape Sequences

Using the code 

string SQL = string.Format("SELECT * FROM Users WHERE UserName='{0}' AND Password='{1}'", MySQLEscape(Username), MySQLEscape(Password));
MySqlCommand cmd = new MySqlCommand(SQL, this.connection);

private static string MySQLEscape(string str)
    return Regex.Replace(str, @"[\x00'""\b\n\r\t\cZ\\%_]",
        delegate(Match match)
            string v = match.Value;
            switch (v)
                case "\x00":            // ASCII NUL (0x00) character
                    return "\\0";   
                case "\b":              // BACKSPACE character
                    return "\\b";
                case "\n":              // NEWLINE (linefeed) character
                    return "\\n";
                case "\r":              // CARRIAGE RETURN character
                    return "\\r";
                case "\t":              // TAB
                    return "\\t";
                case "\u001A":          // Ctrl-Z
                    return "\\Z";
                    return "\\" + v;


A straightforward, though error-prone, way to prevent SQL injections is to escape characters that have a special meaning in SQL.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Member 3783976
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

SuggestionAlternative solution Pin
jmarchaud23-Jul-13 22:28
memberjmarchaud23-Jul-13 22:28 
Questionback slach Pin
oumdaa25-Dec-12 0:37
memberoumdaa25-Dec-12 0:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171020.1 | Last Updated 25 Oct 2012
Article Copyright 2012 by Member 3783976
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid