Introduction
Implement function in C# to emulate functionality of mysql_real_escape_string()
C API function.
Background
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": return "\\0";
case "\b": return "\\b";
case "\n": return "\\n";
case "\r": return "\\r";
case "\t": return "\\t";
case "\u001A": return "\\Z";
default:
return "\\" + v;
}
});
}
Interesting
A straightforward, though error-prone, way to prevent SQL injections is to escape
characters that have a special meaning in SQL.