MySQL 是一个关系型数据库管理系统,广泛用于存储和管理数据。存储图片在 MySQL 中通常涉及将图片文件转换为二进制数据(BLOB,Binary Large Object),然后将其存储在数据库中。
MySQL 中用于存储二进制数据的类型主要有以下几种:
以下是一个简单的示例,展示如何在 MySQL 中存储和读取图片:
import mysql.connector
from mysql.connector import Error
def store_image(image_path, image_id):
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
with open(image_path, 'rb') as file:
binary_data = file.read()
sql_insert_query = """ INSERT INTO images (id, data) VALUES (%s, %s) """
insert_tuple = (image_id, binary_data)
result = cursor.execute(sql_insert_query, insert_tuple)
connection.commit()
print("Image inserted successfully into images table", result)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
store_image('path_to_image.jpg', 1)
import mysql.connector
from mysql.connector import Error
def retrieve_image(image_id, output_path):
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
sql_select_query = """ SELECT data FROM images WHERE id = %s """
cursor.execute(sql_select_query, (image_id,))
record = cursor.fetchone()
if record:
with open(output_path, 'wb') as file:
file.write(record[0])
print("Image retrieved successfully")
else:
print("No image found for the given ID")
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
retrieve_image(1, 'output_image.jpg')
通过以上步骤和示例代码,你可以实现将图片存储到 MySQL 数据库中,并从数据库中读取图片。
领取专属 10元无门槛券
手把手带您无忧上云