我复制了上面的错误:Traceback (most recent call last):
File "demo.py", line 16, in
cursor.execute(query, ())
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte '0xff ... '
in position 0: invalid start byte
使用版本:
^{pr2}$
使用python代码#!/usr/bin/python
# -*- coding: utf-8 -*-
import mysql.connector
conn = mysql.connector.connect(
user='asdf',
password='asdf',
host='1.2.3.4',
database='the_db',
connect_timeout=10)
cursor = conn.cursor(buffered=True) #error is raised here
try:
query = ("SELECT data_blob FROM blog.cmd_table")
cursor.execute(query, ())
except mysql.connector.Error as err: #error is caught here
#error is caught here, and printed:
print(err) #printed thustly
使用python的open(填充的python变量“raw byte binary”如下:def read_file_as_blob(filename):
#r stands for read
#b stands for binary
with open(filename, 'rb') as f:
data = f.read()
return data
所以问题就在文件中数据的编码转换(mysql blob的数据编码)和mysql如何提取blob并将其转换回utf-8之间。在
两种解决方案:
解决方案1正如AHalvar所说,设置use_pure=True参数并传递给mysql.connector.connect( ... )。神秘的是,它真的起作用了。但是优秀的程序员会注意到,遵从神秘咒语是一种不好的代码气味。布朗运动的修正会招致技术债务。在
解决方案2是尽早和经常地对数据进行编码,防止双重重新编码和双重数据解码,这是这些问题的根源。尽快将其锁定为通用的编码格式。在
对我来说,令人满意的解决方案是在这个过程的早期强制utf-8编码。到处执行UTF-8。在data.encode('UTF-8')
unicode文件堆代表了我对在不同操作系统和编码方案上的不同设备之间进行字符编码的这种临时照顾的看法。在