使用 Python 2.7 和 MySQLdb 将二进制数据插入 MySQL 中的 blob 列时如何避免编码警告
How to avoid encoding warning when inserting binary data into a blob column in MySQL using Python 2.7 and MySQLdb
我在使用 Python 2.7 中的 MySQLdb 将二进制数据插入 MySQL 中的 longblob
列时遇到问题,但我收到编码警告我不知道怎么走:
./test.py:11: Warning: Invalid utf8 character string: '8B0800'
curs.execute(sql, (blob,))
这里是 table 定义:
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)"
我在使用 Python 2.7 中的 MySQLdb 将二进制数据插入 MySQL 中的 longblob
列时遇到问题,但我收到编码警告我不知道怎么走:
./test.py:11: Warning: Invalid utf8 character string: '8B0800'
curs.execute(sql, (blob,))
这里是 table 定义:
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)"