MySQL 本身并不直接支持图像文件的存储,但可以通过以下几种方式来保存图像:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
image BLOB
);import mysql.connector
from mysql.connector import Error
import base64
def insert_image(name, file_path):
try:
connection = mysql.connector.connect(host='localhost',
database='your_database',
user='your_username',
password='your_password')
cursor = connection.cursor()
with open(file_path, 'rb') as file:
binary_data = file.read()
encoded_data = base64.b64encode(binary_data)
sql_insert_query = """ INSERT INTO images (name, image) VALUES (%s, %s) """
cursor.execute(sql_insert_query, (name, encoded_data))
connection.commit()
print("Image inserted successfully into images table")
except Error as e:
print(f"Error while connecting to MySQL: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
# 调用函数插入图像
insert_image('example_image', 'path_to_your_image.jpg')import mysql.connector
from mysql.connector import Error
import base64
from PIL import Image
from io import BytesIO
def get_image(image_id):
try:
connection = mysql.connector.connect(host='localhost',
database='your_database',
user='your_username',
password='your_password')
cursor = connection.cursor()
sql_select_query = """ SELECT name, image FROM images WHERE id = %s """
cursor.execute(sql_select_query, (image_id,))
record = cursor.fetchone()
if record:
name, encoded_data = record
binary_data = base64.b64decode(encoded_data)
image = Image.open(BytesIO(binary_data))
image.show()
else:
print("No image found with the given ID")
except Error as e:
print(f"Error while connecting to MySQL: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
# 调用函数获取并显示图像
get_image(1)通过以上方法,你可以在 MySQL 中有效地存储和管理图像数据。
没有搜到相关的文章