使用python中的mysql连接器从mysql数据库正确获取blob

Noc*_*bia 2 python mysql mysql-connector-python

执行以下代码时:

import mysql.connector
connection = mysql.connector.connect(...) # connection params here
cursor = connection.cursor()
cursor.execute('create table test_table(value blob)')
cursor.execute('insert into test_table values (_binary %s)', (np.random.sample(10000).astype('float').tobytes(),))
cursor.execute('select * from test_table')
cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 1 中的字节 0xf7:起始字节无效

(...然后是我认为在这里没有用的堆栈跟踪)

似乎 mysql 连接器将我的 blob 转换为字符串(并且没有这样做)。如何在不进行任何转换的情况下将这些数据作为字节获取?

AHa*_*var 9

我们遇到了同样的问题,即在 MySQL 8.0.13、mysql-connector-python 8.0.13 和 sqlalchemy 1.2.14 中,BLOB 被错误地读回为 UTF-8 字符串。

我们的诀窍是启用use_pure MySQL Connector 选项use_pure8.0.11 中的默认值已更改,新的默认值是使用 C 扩展。因此,我们取消了这个选项:

create_engine(uri, connect_args={'use_pure': True}, ...)
Run Code Online (Sandbox Code Playgroud)

我们的错误和堆栈跟踪的详细信息:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9c in position 1: invalid start byte
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
    ....
    File "/usr/local/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 272, in execute
        self._handle_result(result)
    File "/usr/local/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 163, in _handle_result
        self._handle_resultset()
    File "/usr/local/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 651, in _handle_resultset
        self._rows = self._cnx.get_rows()[0]
    File "/usr/local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 273, in get_rows
        row = self._cmysql.fetch_row()
    SystemError: <built-in method fetch_row of _mysql_connector.MySQL object at 0x5627dcfdf9f0> returned a result with an error set
Run Code Online (Sandbox Code Playgroud)