将图片存入mysql数据库
时间: 2023-05-18 15:03:57 浏览: 118
可以使用BLOB类型的字段将图片存入mysql数据库。首先需要将图片转换为二进制数据,然后将二进制数据插入到BLOB类型的字段中即可。以下是一个示例代码:
```
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='testdb',
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(1, "John", "john_pic.jpg")
```
这个示例代码将名为"john_pic.jpg"的图片插入到名为"employees"的表中的BLOB类型字段"photo"中。
阅读全文