简体   繁体   English

使用UPDATE时转义mysql语句中的特殊字符

[英]escaping special character in mysql statements while using UPDATE

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. 这里的问题是some_variable包含其中包含多个特殊字符的数据。 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? 因此我无法使用'some_variable'或“ some_variable”,因为遇到第一个相同字符('或“)时它会破裂并失败。我该如何克服呢?

Thanks. 谢谢。 Mike 麦克风

There are two solutions, the first is to use mysql_real_escape_string() the second is to use prepared statements. 有两种解决方案,第一种是使用mysql_real_escape_string() ,第二种是使用准备好的语句。 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: 除实际转义外,如果您的字段是char或varchar,则应按以下方式修改查询:

UPDATE table set field='some_variable' where id=1;

Generally, you just need to escape the reserved characters -- see MySQL docs for specific reference. 通常,您只需要转义保留的字符-有关特定参考,请参见MySQL文档 If you are directly executing the query (ie: in mysql shell), you'll have to escape manually. 如果您直接执行查询(即:在mysql shell中),则必须手动进行转义。 Most languages will supply a function to escape for you -- in PHP, for example, it's mysql_real_escape_string() . 大多数语言都会为您提供转义功能-例如,在PHP中,它是mysql_real_escape_string()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM