如果我在 MySQL 中使用二进制数据创建一个简单的表:
CREATE TABLE foo ( bar binary(4) )
INSERT INTO foo (bar) VALUES ( UNHEX('de12') )
然后尝试使用 MySQL Connector/Python 读取它:
import mysql.connector
conn = mysql.connector.connect(database='test', user='test')
cursor = conn.cursor()
cursor.execute("SELECT * FROM foo")
cursor.fetchall()
我收到此错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xde in position 0: invalid continuation byte
我不明白为什么 Python MySQL 连接器尝试将该列解码为 UTF-8。我只想获取原始二进制数据,我该怎么做?
(Python 2.7.10、Mysql 5.7.22、MySQL 连接器/Python 8.0.12)
最佳答案
使用原始连接(或原始游标)来执行提取。
import mysql.connector
conn = mysql.connector.connect(database='test',
user='test',raw=True)
cursor = conn.cursor()
cursor.execute("SELECT * FROM foo")
cursor.fetchall()
默认情况下,python fetch 命令尝试将二进制数据转换为字符串。当它尝试这样做时,它遇到了 utf-8 编码字符串中不允许的字节序列。将原始模式设置为 True
会覆盖此行为,并使结果按原样返回,而不是转换为 Python 类型。
关于python - 如何使用 Mysql Python 连接器检索二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51657097/