如何在MySQL中插入特殊字符(例如')? [英] How do I insert a special character such as ' into MySQL?

查看:276
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆