pymysql 是一个用于连接 MySQL 数据库的 Python 库。要使用 pymysql 存储图片,通常的做法是将图片转换为二进制数据(bytes),然后将其存储在数据库的 BLOB(Binary Large Object)类型字段中。
open 函数以二进制模式('rb')打开图片文件,读取其内容。import pymysql
# 连接到 MySQL 数据库
conn = pymysql.connect(host='localhost', user='username', password='password', db='database_name')
# 创建一个游标对象
cursor = conn.cursor()
# 打开图片文件并读取为二进制数据
with open('path_to_image.jpg', 'rb') as file:
image_data = file.read()
# 执行 SQL 插入语句
sql = "INSERT INTO images (name, data) VALUES (%s, %s)"
cursor.execute(sql, ('image_name.jpg', image_data))
# 提交事务
conn.commit()
# 关闭游标和数据库连接
cursor.close()
conn.close()FileNotFoundError。pymysql.err.OperationalError。pymysql.err.ProgrammingError。通过以上步骤和示例代码,你可以使用 pymysql 将图片存储到 MySQL 数据库中。
没有搜到相关的文章