如何在 Python 的 MySQL 的 BLOB 列中插入 b'\x1bB\x85'?

How to insert b'\x1bB\x85' in MySQL's BLOB column from Python?

我正在尝试使用 pymysql.

在 Python 中的 BLOB 类型列中插入 bytes

要求是插入时字节不要编码

我的SQL执行时如下所示:

insert into product values(b'<\xf0Q,\x18\x99y\x86\xda\x81\xc8\x869Q\xf8\xc9\xb2\xc6NqG\xcfV\xbf{\x86\xf8\nJ\x0b\xfa)');

尝试插入时出现以下错误。


    cursor.execute(sql)
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/cursors.py", line 148, in execute
    result = self._query(query)
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/cursors.py", line 310, in _query
    conn.query(q)
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/connections.py", line 548, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/connections.py", line 775, in _read_query_result
    result.read()
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/connections.py", line 1156, in read
    first_packet = self.connection._read_packet()
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/connections.py", line 725, in _read_packet
    packet.raise_for_error()
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/protocol.py", line 221, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "home/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'b'<\xf0Q,\x18\x99y\x86\xda\x81\xc8\x869Q\xf8\xc9\xb2\xc6NqG\xcfV\xbf{\x86\xf8\nJ' at line 1")

如果使用参数替换,pymysql 将正确处理字节。

>>> import pymysql
>>> conn = pymysql.connect(database='test')
>>> cur = conn.cursor()
>>> cur.execute("""CREATE TABLE t70182867 (id int not null auto_increment, data blob, primary key(id))""")
0
>>> bs = b'<\xf0Q,\x18\x99y\x86\xda\x81\xc8\x869Q\xf8\xc9\xb2\xc6NqG\xcfV\xbf{\x86\xf8\nJ\x0b\xfa)'
>>> sql = """INSERT INTO t70182867 (data) VALUES (%s)"""
>>> cur.execute(sql, (bs,))  # <= let pymysql handle the values
1
>>> conn.commit()
>>> cur.execute("""SELECT data FROM t70182867""")
1
>>> cur.fetchone()
(b'<\xf0Q,\x18\x99y\x86\xda\x81\xc8\x869Q\xf8\xc9\xb2\xc6NqG\xcfV\xbf{\x86\xf8\nJ\x0b\xfa)',)
>>>