mysql - 如何转义 MySQL 中的特殊字符?

标签 mysql

例如:

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

错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'hi" "' at line 1

如何构建此查询?

最佳答案

The information provided in this answer can lead to insecure programming practices.

The information provided here depends highly on MySQL configuration, including (but not limited to) the program version, the database client and character-encoding used.

参见 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.

So you need

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

虽然作为Bill Karwin notes below , 对字符串分隔符使用双引号不是标准 SQL,因此最好使用单引号。这简化了事情:

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

关于mysql - 如何转义 MySQL 中的特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33372073/

相关文章:

mysql - 在 MySql 存储过程中循环错误代码 1064

Python Flask 未返回 MySQL 请求的有效响应

PHP读取XML并写入数据库

mysql - SQL 语句 Max(Count(*))

javascript - 得到“未定义ReferenceError”

php - 数据没有上传到mysql

mysql 外键错误 150

mysql - Django 为 OR 子句生成慢查询(左外连接而不是联合)

mysql - 查找所有丢失的映射表条目

php - Laravel ownsToMany 插入查询中的表顺序