我在使用 Python 2.7 中的 MySQLdb 将二进制数据插入 MySQL 中的 longblob
列时遇到问题,但收到一条编码警告,但我不知道如何解决:
./test.py:11: Warning: Invalid utf8 character string: '8B0800'
curs.execute(sql, (blob,))
这是表定义:
CREATE TABLE test_table (
id int(11) NOT NULL AUTO_INCREMENT,
gzipped longblob,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
测试代码:
#!/usr/bin/env python
import sys
import MySQLdb
blob = open("/tmp/some-file.gz", "rb").read()
sql = "INSERT INTO test_table (gzipped) VALUES (%s)"
conn = MySQLdb.connect(db="unprocessed", user="some_user", passwd="some_pass", charset="utf8", use_unicode=True)
curs = conn.cursor()
curs.execute(sql, (blob,))
我在这里和其他地方搜索了答案,但不幸的是,尽管许多问题似乎正是我正在寻找的问题,但海报似乎没有编码问题。
问题:
- 是什么原因导致此警告?
- 如何摆脱它?
最佳答案
经过更多搜索,我找到了答案。
- 实际上是 MySQL 生成了此警告。
- 可以通过在二进制参数前使用
_binary
来避免这种情况。
https://bugs.mysql.com/bug.php?id=79317
因此Python代码需要更新如下:
sql = "INSERT INTO test_table (gzipped) VALUES (_binary %s)"
关于mysql - 使用 Python 2.7 和 MySQLdb 将二进制数据插入 MySQL 中的 blob 列时如何避免编码警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192861/