我有一个[legacy] mysql表,其字符集为“latin-1”
,但将json信息存储在“utf-8”
中。用户界面连接到该表,该表正确显示字符。我需要使用 python 脚本更新此表,但我无法摆脱编码 hell 。
在 mysql shell 上,我发出 "select Words from pip where id_pip=42"
并接收:
"ventilationsplåtslageri":{"day":"1000","hour":"200","min":"30"}
但是当我尝试从数据库中获取它时,即使我尝试了几种不同的编码,我也无法获得相同的编码。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import json
dbconn = MySQLdb.connect(host="host",port=3306,user="user",
passwd="pass",db="db", use_unicode=True, charset="utf8")
cursor1 = dbconn.cursor()
cursor1.execute("select words from pip where id_pip=42")
track = cursor1.fetchall()
print json.dumps(track, encoding="utf8" )
我在此代码上尝试了许多不同的配置,例如我用 print json.dumps(filter_track,encoding="utf8")
更改了 "use_unicode=False, charset="latin1"
但我仍然得到 "ventilationspl\u00c3\u00a5tslageri\"
或 "ventilationspl\u00e5tslageri\"
而不是我想要的:"ventilationsplàtslageri"
我无法更改数据库,并且需要使用 sql update 命令更新数据库的该字段,所以我担心如果我弄乱了旧数据库。
最佳答案
我不确定我是否理解你的问题,但是......
如果内容以 Latin-1 格式返回,而您希望以 UTF-8 格式返回,我假设您首先需要解码来自Latin-1,然后将其编码为 UTF-8。
latin1_content.decode('latin1').encode('utf8')
关于python - 使用 latin1 字符集对表中的 UTF8 数据进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081887/