![](/img/trans.png)
[英]How to insert / retrieve a file stored as a BLOB in a MySQL db using python
[英]Can't insert blob image using Python via stored procedure mysql
我正在尝试使用存储过程将图像插入mysql的blob列中。
Python代码:
from mysql.connector import pooling
conn_pool = pooling.MySQLConnectionPool(pool_name="PipelinePool", pool_size=5, **DB_CONFIG)
conn = conn_pool.get_connection()
cursor = conn.cursor()
with open('test.jpg', 'rb') as image_file:
image = image_file.read()
cursor.callproc('INSERT_IMG', args=(image))
conn.commit()
cursor.callproc('INSERT_IMG', args=(image))
但是这一行会产生错误:
mysql.connector.errors.InterfaceError:调用存储例程失败; 'utf8'编解码器无法解码位置0的字节0xff:无效的起始字节
存储过程代码:
CREATE PROCEDURE `INSERT_IMG` (IN _image BLOB)
BEGIN
INSERT INTO some_table (IMAGE) VALUE (_image);
END
解决了。 根据塔德曼的评论。
我必须发送十六进制字符串作为参数。
from mysql.connector import pooling
import binascii
conn_pool = pooling.MySQLConnectionPool(pool_name="PipelinePool", pool_size=5, **DB_CONFIG)
conn = conn_pool.get_connection()
cursor = conn.cursor()
with open('test.jpg', 'rb') as image_file:
image = image_file.read()
cursor.callproc('INSERT_IMG', args=(binascii.hexlify(image)))
conn.commit()
然后在存储过程中,我使用UNHEX()
将十六进制字符串转换为二进制。
CREATE PROCEDURE `INSERT_IMG` (IN _image BLOB)
BEGIN
INSERT INTO some_table (IMAGE) VALUE (UNHEX(_image));
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.