簡體   English   中英

如何在 MySQL 中轉義特殊字符?

[英]How do I escape special characters in MySQL?

例如:

select * from tablename where fields like "%string "hi"  %";

錯誤:

您的 SQL 語法有錯誤; 檢查與您的 MySQL 服務器版本相對應的手冊,以在第 1 行的 'hi" "' 附近使用正確的語法

如何構建此查詢?

此答案中提供的信息可能會導致不安全的編程實踐。

此處提供的信息高度依賴於 MySQL 配置,包括(但不限於)程序版本、數據庫客戶端和使用的字符編碼。

請參閱http://dev.mysql.com/doc/refman/5.0/en/string-literals.html

MySQL recognizes the following escape sequences.
\0     An ASCII NUL (0x00) character.
\'     A single quote (“'”) character.
\"     A double quote (“"”) character.
\b     A backspace character.
\n     A newline (linefeed) character.
\r     A carriage return character.
\t     A tab character.
\Z     ASCII 26 (Control-Z). See note following the table.
\\     A backslash (“\”) character.
\%     A “%” character. See note following the table.
\_     A “_” character. See note following the table.

所以你需要

select * from tablename where fields like "%string \"hi\" %";

盡管正如Bill Karwin 下面所指出的,對字符串定界符使用雙引號並不是標准 SQL,因此使用單引號是一種很好的做法。 這簡化了事情:

select * from tablename where fields like '%string "hi" %';
["

private static final HashMap<String,String> sqlTokens;
private static Pattern sqlTokenPattern;

static
{           
    //MySQL escape sequences: http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
    String[][] search_regex_replacement = new String[][]
    {
                //search string     search regex        sql replacement regex
            {   "\u0000"    ,       "\\x00"     ,       "\\\\0"     },
            {   "'"         ,       "'"         ,       "\\\\'"     },
            {   "\""        ,       "\""        ,       "\\\\\""    },
            {   "\b"        ,       "\\x08"     ,       "\\\\b"     },
            {   "\n"        ,       "\\n"       ,       "\\\\n"     },
            {   "\r"        ,       "\\r"       ,       "\\\\r"     },
            {   "\t"        ,       "\\t"       ,       "\\\\t"     },
            {   "\u001A"    ,       "\\x1A"     ,       "\\\\Z"     },
            {   "\\"        ,       "\\\\"      ,       "\\\\\\\\"  }
    };

    sqlTokens = new HashMap<String,String>();
    String patternStr = "";
    for (String[] srr : search_regex_replacement)
    {
        sqlTokens.put(srr[0], srr[2]);
        patternStr += (patternStr.isEmpty() ? "" : "|") + srr[1];            
    }
    sqlTokenPattern = Pattern.compile('(' + patternStr + ')');
}


public static String escape(String s)
{
    Matcher matcher = sqlTokenPattern.matcher(s);
    StringBuffer sb = new StringBuffer();
    while(matcher.find())
    {
        matcher.appendReplacement(sb, sqlTokens.get(matcher.group(1)));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

您應該使用單引號作為字符串分隔符。 單引號是標准的 SQL 字符串分隔符,雙引號是標識符分隔符(因此您可以在表或列的名稱中使用特殊單詞或字符)。

在 MySQL 中,默認情況下,雙引號(非標准)用作字符串分隔符(除非您設置ANSI SQL 模式)。 如果您曾經使用過其他品牌的 SQL 數據庫,那么您將受益於養成標准使用引號的習慣。

使用單引號的另一個方便的好處是字符串中的文字雙引號字符不需要轉義:

select * from tablename where fields like '%string "hi" %';

MySQL 有字符串函數QUOTE ,應該可以解決問題

對於這樣的字符串,對我來說最舒服的方法是將'或'加倍,如 MySQL 手冊中所述:

有幾種方法可以在字符串中包含引號字符:

 A “'” inside a string quoted with “'” may be written as “''”. A “"” inside a string quoted with “"” may be written as “""”. Precede the quote character by an escape character (“\”). A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a

用“'”引用的字符串不需要特殊處理。

它來自http://dev.mysql.com/doc/refman/5.0/en/string-literals.html

您可以使用mysql_real_escape_string mysql_real_escape_string()不會轉義%_ ,因此您應該分別轉義 MySQL 通配符( %_ )。

為了測試如何使用終端在 MySQL 中插入雙引號,可以使用以下方式:

表名(名稱,DString)-> 架構
插入 TableName 值("Name","My QQDoubleQuotedStringQQ")

插入值后,您可以使用雙引號或單引號更新數據庫中的值:

update table TableName replace(Dstring, "QQ", "\"")

如果您在搜索字符串時使用變量,則mysql_real_escape_string()對您有好處。 只是我的建議:

$char = "and way's 'hihi'";
$myvar = mysql_real_escape_string($char);

select * from tablename where fields like "%string $myvar  %";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM