【发布时间】:2015-10-12 13:04:39
【问题描述】:
我有一个 [legacy] mysql 表,其字符集为 "latin-1",但将 json 信息存储在 "utf-8" 中。用户界面连接到该表,该表正确显示字符。我需要使用 python 脚本更新此表,但我无法摆脱编码地狱。
在 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" )
我在这段代码上尝试了许多不同的配置,例如我将"use_unicode=False, charset="latin1" 更改为print json.dumps(filter_track, encoding="utf8" ) 但我仍然得到"ventilationspl\u00c3\u00a5tslageri\" 或"ventilationspl\u00e5tslageri\" 而不是我想要的:"ventilationsplÃ¥tslageri"
我无法更改数据库,我需要使用 sql update 命令更新数据库的这个字段,所以我担心如果我搞砸了旧数据库。
【问题讨论】:
标签: python mysql utf-8 character-encoding