如何将图片保存到mysql数据库中
时间: 2024-03-16 08:44:00 浏览: 61
将图片保存到MySQL数据库中,可以采用以下步骤:
1. 将图片转换成二进制数据。
2. 创建一个BLOB类型的字段来存储二进制数据。
3. 使用INSERT语句将二进制数据插入到BLOB字段中。
以下是一个示例代码:
```python
import mysql.connector
from mysql.connector import Error
def convertToBinaryData(filename):
# 将图片转换成二进制数据
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData
def insertBLOB(emp_id, name, photo):
try:
connection = mysql.connector.connect(host='localhost',
database='test',
user='root',
password='password')
cursor = connection.cursor()
sql_insert_blob_query = """ INSERT INTO employees
(id, name, photo) VALUES (%s,%s,%s)"""
empPicture = convertToBinaryData(photo)
# 插入二进制数据到BLOB字段中
insert_blob_tuple = (emp_id, name, empPicture)
result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
connection.commit()
print("Image and file inserted successfully as a BLOB into employees table", result)
except mysql.connector.Error as error:
print("Failed inserting BLOB data into MySQL table {}".format(error))
finally:
# 关闭数据库连接
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
# 调用 insertBLOB 函数插入二进制数据到BLOB字段中
insertBLOB(1, "John", "/path/to/image.jpg")
```
请注意,此示例仅供参考,并且可能需要根据您的数据库架构和需求进行更改。
阅读全文