【问题标题】:Encoding UTF8 data within a table with latin1 character set使用 latin1 字符集在表中编码 UTF8 数据
【发布时间】: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


    【解决方案1】:

    我不确定我是否理解你的问题,但是......

    如果内容以 Latin-1 格式返回并且您希望它以 UTF-8 格式返回,我假设您首先需要从Latin-1 然后将其编码为 UTF-8。

    latin1_content.decode('latin1').encode('utf8')
    

    【讨论】:

    • 感谢您的回答,但我认为这不能解决问题。也许我混淆了 latin-1 内容。为什么我不能配置 MySQLdb 以返回与 Mysql shell 相同的结果。使用相同的查询,我看到不同的结果。 Mysql: 通风splÃ¥tslageri 和蟒蛇通风spl\u00c3\u00a5tslageri\
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2012-05-18
    • 2019-12-18
    • 2015-09-29
    相关资源
    最近更新 更多