python - 如何使用 Mysql Python 连接器检索二进制数据?

标签 python mysql

如果我在 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/

相关文章:

python - 如何在 Spark 中使用 Sklearn 模型进行预测?

python - Seaborn 堆叠直方图/条形图

mysql - 如何在循环中运行 SQL 查询

mysql - 在没有设置任何数据库的情况下,如何将 CSV 文件转换为基于 Web 的 SQL 数据库表?

mysql - 选择具有最大 id 值的表行

python - Rails 和 NLTK 部署到 Heroku

python - 如何在 python 中使用变量作为文件名的一部分打开文件?

python - 使用参数访问基于类的装饰器的属性

mysql - SUM 列值与 group by aggregate 处理空值

php - mySQL inner join with where条件不起作用