在MySQL中添加图片通常涉及到将图片文件存储为二进制数据(BLOB)。以下是详细步骤和相关概念:
TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB,根据图片大小选择合适的类型。TINYBLOB:最大长度为255字节。BLOB:最大长度为65,535字节(约64KB)。MEDIUMBLOB:最大长度为16,777,215字节(约16MB)。LONGBLOB:最大长度为4,294,967,295字节(约4GB)。CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
image BLOB
);import mysql.connector
from mysql.connector import Error
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()
sql_insert_query = """ INSERT INTO images (name, image) VALUES (%s, %s) """
insert_tuple = (name, binary_data)
result = cursor.execute(sql_insert_query, insert_tuple)
connection.commit()
print("Image inserted successfully into images table")
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")
# 使用示例
insert_image('example.jpg', 'path/to/example.jpg')import mysql.connector
from mysql.connector import Error
from PIL import Image
import io
def retrieve_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, image = record
image_file = io.BytesIO(image)
img = Image.open(image_file)
img.show()
else:
print("No image found with 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)通过以上步骤和示例代码,你可以在MySQL中成功添加和检索图片。
没有搜到相关的沙龙