开发者

C# equivalent to php mysql_real_escape_string function?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜