如何在MySQL中插入特殊字符(例如')? [英] How do I insert a special character such as ' into MySQL?
问题描述
我正在从一个外壳脚本执行insert
查询,该脚本从多个文件中读取数据.某些要插入的数据在文本中包含'
,而MySQL不断给出错误信息
I am executing the insert
query from a shell script which reads data from multiple files. Some of the data to be inserted contains '
in the text and MySQL keeps giving errors
ERROR 1064 (42000) at line 1: 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 's Development & Empowerment, Youth Affairs
','
Himachal Pradesh ' at line 1
这是实际的文本:Women's Development & Empowerment, Youth Affairs
.
推荐答案
您需要对引号进行转义,如下所示:
You need to escape the quote, like so:
'Women\'s Development & Empowerment, Youth Affairs'
请注意,如果要从PHP之类的语言生成SQL语句,则可以使用一些函数来完成此操作.
Note, that if you're generating the SQL statement from a language like PHP, there are functions available to do this for you.
例如,在PHP中,有 mysql_real_escape_string ,它会为您处理.请注意,准备好的语句比这更可取,因为更难弄错这些语句.
In PHP, for instance, there is mysql_real_escape_string, which takes care of it for you. Note, that prepared statements are to be prefered over this, as it's harder to get those wrong.
另请参阅:
- The MySQL manual entry on strings
- PHP PDO prepared statements
这篇关于如何在MySQL中插入特殊字符(例如')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!