Blob(Binary Large Object)是一种数据类型,用于存储大量的二进制数据,如图片、音频、视频等。在MySQL数据库中,可以使用BLOB类型来存储这些数据。
以下是一个简单的示例,展示如何将图片存储到MySQL数据库中:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
image BLOB
);
import mysql.connector
from mysql.connector import Error
def store_image(image_path):
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_blob_query = """ INSERT INTO images
(name, image) VALUES (%s,%s)"""
insert_blob_tuple = (image_path, binary_data)
result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
connection.commit()
print("Image and file inserted successfully as id: %s" % 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_your_image.jpg')
def retrieve_image(image_id):
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
sql_select_blob_query = """SELECT name, image from images where id = %s"""
cursor.execute(sql_select_blob_query, (image_id,))
record = cursor.fetchall()
for row in record:
print("Image Name: ", row[0])
image_name = row[0]
with open(f'retrieved_{image_name}', 'wb') as file:
file.write(row[1])
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)
通过以上内容,你应该对Blob图片存储到MySQL有了全面的了解,并且知道如何解决常见问题。
领取专属 10元无门槛券
手把手带您无忧上云