0

C# equivalent to php mysql_real_escape_string function or similar function?

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

1

2 Answers 2

0

I don't think there is anything that does that, there are various encoding/escaping methods in the System.Web.HttpUtility class. However if it is just those characters you want to replace you could use string.Replace()

e.g.

string test = " \x00\n";
Console.WriteLine(test.Replace("\x00","\\x00").Replace("\n","\\n"));
Sign up to request clarification or add additional context in comments.

4 Comments

-1: This is certainly not the equivalent of mysql_real_escape_string. If it were, we 'd all be using addslashes or some such.
I have no idea what mysql_real_escape_string does other than the description supplied by the OP, thus i have supplied a solution that matches his description. Notice i frame the answer "if it is just those characters you want to replace"...
@Jon i just had a quick look at the PHP manual and it says mysql_real_escape_string works as the OP describes. In fact as far as i can tell from the manual the difference between addslashes and mysql_real_escape_string is the the latter also escapes \n \r and \x1a. If there are other differences please feel free to explain them.
mysql_real_escape_string takes the MySQL connection encoding into account (it says so in the very first line). Contrast this with mysql_escape_string, which is the equivalent of string.Replace, works exactly like you describe and has been deprecated because it is unsafe.
0

I use this function:

public 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";
                default:
                    return "\\" + v;
            }
        });
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.