从远程数据库获取UTF8字符串
我的应用程序从远程 MySQL 数据库下载一些数据。问题是 db 将字符串存储为 utf8。但我收到的数据是 ascii 解码的。如何解决这个问题?
代码:
cursor = conn.cursor()
query = """MY QUERY HERE"""
cursor.execute(query)
result = cursor.fetchall()
My application downloads some data from remote MySQL database. Problem is that db stores strings as utf8. But data I receive is ascii decoded. How to get around this ?
The code :
cursor = conn.cursor()
query = """MY QUERY HERE"""
cursor.execute(query)
result = cursor.fetchall()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许有一个例子——这里我创建了一个unicode字符串“u”,将其编码为utf8,将其从utf8解码回unicode字符串,将其编码为ascii(这会引发异常,因为该字符串中的扩展字符可以不被编码为ascii),然后最后编码为ascii,用“?”替换错误:
大概,您从数据库中获取utf8字符串,您应该将它们从utf8解码为unicode字符串,然后可能重新编码它们在输出上用于消耗程序输出的任何内容...通常您需要一个类似以下的模型:
这为您提供了编码/解码的清晰分离,并避免将编码处理代码传播到整个应用程序,因为核心只处理 unicode 。
Perhaps an example is in order -- here I create a unicode string "u", encode it as utf8, decode that from utf8 back to a unicode string, encode it as ascii (which throws an exception since the extended character in this string can't be encoded as ascii), then finally encode as ascii replacing errors with the "?":
Presumably, you're getting utf8 strings back from the db, you should decode these from utf8 to a unicode string, then probably re-encode them on output for whatever is consuming the output of your program... Typically you want a model something like:
This gives you a clean separation of encoding/decoding and avoids spreading encoding-handling code all over your application since the core only deals with unicode.
您可能想尝试
string.encode('ascii').decode('utf-8')
?You might want to try
string.encode('ascii').decode('utf-8')
?在从数据库查询之前执行
conn.set_character_encoding('utf8')
。do a
conn.set_character_encoding('utf8')
before querying from the db.只需将你的Python设置为utf-8编码,你就不用再担心了。使用 db2/ mongodb 加载数据时遇到此问题。
只需将 site.py 下的默认编码设置为 utf-8 即可。
看看@ http://blog.ianbicking.org/illusive-setdefaultencoding.html
just set your python to utf-8 encoding and you don't have to worry anymore. had this problem with db2/ mongodb to load data.
just set the defaultencoding to utf-8 under site.py.
have a look @ http://blog.ianbicking.org/illusive-setdefaultencoding.html