在MySQL中存储图片,通常有以下几种字段类型和相关考虑因素:
以下是一个简单的示例,展示如何在MySQL中存储和检索图片:
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
with open('path_to_image.jpg', 'rb') as file:
binary_data = file.read()
insert_query = "INSERT INTO images (image) VALUES (%s)"
cursor.execute(insert_query, (binary_data,))
connection.commit()
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")import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
select_query = "SELECT image FROM images WHERE id = %s"
cursor.execute(select_query, (1,))
record = cursor.fetchone()
if record:
with open('retrieved_image.jpg', 'wb') as file:
file.write(record[0])
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")希望这些信息对你有所帮助!
没有搜到相关的文章