mysql中表mtable中有两个字段id (int),photo (blob);python中如何把2个图片,存到mtable中为id=1的同一条记录中photo的字段中,请给出代码
时间: 2024-05-05 14:15:04 浏览: 77
假设已经连接到了MySQL数据库,表名为mtable,可以使用以下代码将两张图片存储到id为1的记录中:
```python
import mysql.connector
from mysql.connector import Error
# 读取图片文件
with open('photo1.jpg', 'rb') as f1:
photo1 = f1.read()
with open('photo2.jpg', 'rb') as f2:
photo2 = f2.read()
# 连接数据库
try:
connection = mysql.connector.connect(
host='localhost',
database='mydb',
user='root',
password='password'
)
if connection.is_connected():
print('Connected to MySQL database')
# 将图片存储到数据库中
cursor = connection.cursor()
sql = "UPDATE mtable SET photo = %s WHERE id = 1"
values = (photo1 + photo2,)
cursor.execute(sql, values)
connection.commit()
print('Photos saved to database')
except Error as e:
print('Error while connecting to MySQL', e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print('MySQL connection closed')
```
以上代码将图片文件读取为二进制数据,然后使用UPDATE语句将两张图片拼接为一个二进制字符串,存储到id为1的记录的photo字段中。注意要将两张图片拼接为一个元组再传入execute函数中。
阅读全文