使用 UPDATE 时转义 mysql 语句中的特殊字符
我正在尝试使用更新字段。
UPDATE table set field='some_variable' where id=1;
这里的问题是 some_variable 包含带有多个特殊字符的数据。所以我无法使用“some_variable”或“some_variable”,因为当它遇到第一个相同的字符('或“)时它会中断并失败。我该如何克服这个问题?
谢谢。 麦克风
I am trying to update a field using
UPDATE table set field='some_variable' where id=1;
The problem here is that the some_variable comtains data with multiple special characters in it. so I am not able to use 'some_variable' or "some_variable" as it breaks and fails when it encounters the first same character(' or "). How can I overcome this?
Thanks.
Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种解决方案,第一种是使用mysql_real_escape_string(),第二种是使用准备好的语句。您还没有提到您的编程语言是什么,但它肯定支持准备好的语句或真正的转义。
除了真正的转义之外,如果您的字段是 char 或 varchar,您应该按如下方式修改查询:
There are two solutions, the first is to use
mysql_real_escape_string()
the second is to use prepared statements. You have not mentioned what your programming language is but it's sure to support either prepared statements or real escape.In addition to real escape, if your field is a char or varchar you should modify your query as follows:
一般来说,您只需要转义保留字符 - 请参阅 MySQL docs 以供具体参考。如果您直接执行查询(即:在 mysql shell 中),则必须手动转义。大多数语言都会提供一个函数来为您转义——例如,在 PHP 中,它是
mysql_real_escape_string()
。Generally, you just need to escape the reserved characters -- see MySQL docs for specific reference. If you are directly executing the query (ie: in mysql shell), you'll have to escape manually. Most languages will supply a function to escape for you -- in PHP, for example, it's
mysql_real_escape_string()
.