MySQL是一种关系型数据库管理系统,广泛用于存储和管理数据。将图片存入MySQL数据库中,通常有两种方式:
优势:
类型:
TINYBLOB
:最大长度为 255 字节。BLOB
:最大长度为 65,535 字节(64KB)。MEDIUMBLOB
:最大长度为 16,777,215 字节(16MB)。LONGBLOB
:最大长度为 4,294,967,295 字节(4GB)。优势:
import mysql.connector
from mysql.connector import Error
def store_image_in_db(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()
insert_query = "INSERT INTO images (name, data) VALUES (%s, %s)"
cursor.execute(insert_query, (image_path, binary_data))
connection.commit()
print("Image stored successfully.")
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
store_image_in_db('path_to_image.jpg')
import mysql.connector
from mysql.connector import Error
def store_image_path_in_db(image_path):
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='password')
cursor = connection.cursor()
insert_query = "INSERT INTO images (name, path) VALUES (%s, %s)"
cursor.execute(insert_query, (image_path, image_path))
connection.commit()
print("Image path stored successfully.")
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
store_image_path_in_db('path_to_image.jpg')
原因:
解决方法:
原因:
解决方法:
希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云