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(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()
insert_query = "INSERT INTO images (name, data) VALUES (%s, %s)"
cursor.execute(insert_query, (file_path, 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")
store_image('path_to_image.jpg')
import mysql.connector
from mysql.connector import Error
def store_image_path(file_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, (file_path, file_path))
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")
store_image_path('path_to_image.jpg')
原因:
解决方法:
原因:
解决方法:
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云