python3使用MySQLdb库查询时报UnicodeDecodeError错误

问题描述

在使用MySQLdb库连接mysql查询数据时,会报错:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte

python脚本如下:

import MySQLdb

conn = MySQLdb.connect(host="xxx", port=xxx, user="xxx", passwd="xxx", db="xxx", charset="utf8")
cur = conn.cursor()
cur.execute("select name from test_tb")
result = cur.fetchall()
for row in result:
    print(row[0])
conn.close()

模拟此问题的数据:

-- utf8编码的'你好'
replace into test_tb(id,name) values(1,0xc4e3bac3);
-- gbk编码的'你好'
replace into test_tb(id,name) values(2,0xe4bda0e5a5bd);

查看代码

当前使用的mysqlclient-1.4.6版本,查看mysqlclient-1.4.6/MySQLdb/_mysql.c中代码后发现是转码时指定的参数有问题:

将NULL改为"replace"后重新编译mysqlclient安装,就不报错了,不过得到的结果有乱码:

���
你好
posted @ 2022-08-05 18:01  bug批发零售  阅读(263)  评论(0)    收藏  举报