清理 UTF-8 编码字符串
我想在将 UTF-8 编码的字符串用作 MySQL SELECT 语句的一部分之前对其进行清理。
例如,我有:
query = MySQLdb.escape_string(query)
但这行会导致引发异常,内容为
“ascii”编解码器无法对位置 0-2 中的字符进行编码:序号不在 范围(128)。
我该如何处理这个问题?
I want to sanitise a UTF-8 encoded string before using it as part of a MySQL SELECT statement.
For example, I have:
query = MySQLdb.escape_string(query)
but this line is leading to a raised exception that reads
'ascii' codec can't encode characters in position 0-2: ordinal not in
range(128).
How can I handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来 MySQLdb 正在尝试将您的 unicode 查询编码为字符串。为此,它使用默认编码:ASCII。
现在,您的输入无法编码为 ASCII,因此您只需告诉 python 它应该使用什么编码:utf-8。
您可以使用
query = query.encode('utf-8') 来实现此目的。
Looks like MySQLdb is trying to encode your unicode query to a string. To do so it's using the default encoding: ASCII.
Now, your input can't be encoded into ASCII, so you just need to tell python what encoding it should use: utf-8.
You can achieve this by using
query = query.encode('utf-8').
在您的示例中,
query
的类型为“str”。如果在字符串前面加上“u”,它就会成为“unicode”类型。这是 Python 2.x 和 3.x 版本之间的主要区别之一。从 3.0 开始,所有字符串默认都是“unicode”。
In your example
query
is of type 'str'. If you put a 'u' before the string, it becomes of type 'unicode'.This is one of the main differences between Python versions 2.x and 3.x. Starting in 3.0, all strings are 'unicode' by default.