开发者

C# equivalent to php mysql_real_escape_string function?

开发者 https://www.devze.com 2023-03-30 10:47 出处:网络
C# equivalent to php mysql_real_escape_string 开发者_如何学Pythonfunction or similar function? mysql_real_escape_string() calls MySQL\'s library function mysql_real_escape_string, which prepends back

C# equivalent to php mysql_real_escape_string 开发者_如何学Pythonfunction 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.


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;
            }
        });
} 


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"));
0

精彩评论

暂无评论...
验证码 换一张
取 消