MySQL 是一个关系型数据库管理系统,用于存储和管理数据。在 MySQL 中,图片通常以二进制大对象(BLOB)的形式存储。BLOB 是一种数据类型,用于存储大量的二进制数据,如图片、音频和视频文件。
MySQL 中用于存储图片的数据类型主要有:
-- 创建表
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
image BLOB
);
-- 插入数据
INSERT INTO images (name, image) VALUES (?, ?);
import mysql.connector
from mysql.connector import Error
def insert_image(name, file_path):
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
with open(file_path, 'rb') as file:
binary_data = file.read()
query = "INSERT INTO images (name, image) VALUES (%s, %s)"
cursor.execute(query, (name, binary_data))
connection.commit()
print("Image inserted successfully")
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
# 使用示例
insert_image('example.jpg', '/path/to/example.jpg')
通过以上步骤和示例代码,你可以成功地将图片导入到 MySQL 数据库中。如果遇到问题,可以根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云