MySQL has a storage type called MediumBlob, which can be used to store other files such as binary formats.
Upload: Turn from the picture format to a binary format, and then store in the database.
download: Get the picture from the database to the binary format, and then convert it into a picture format.
import pymysql
'' '
Establish a binary mode of the table statement ID title picture
Create Table Pictures (PID Int Primary Key Auto_increment, Ptitle Varchar (255), Picturesbyte Mediumblob)
'' '
# connection database
conn = pymysql.connect(
host="localhost",
user="root",
password="123456",
database="QianFuXin",
charset="utf8")
# get a cursor object that can execute SQL statements
cursor = conn.cursor()
# Upload pictures to the database
def uploadPicture(picturePath, PTitle):
# Read the picture and save it into binary
picture = open(picturePath, 'rb')
pictureByte = picture.read()
picture.close()
# Insert binary files into the database
query = 'insert into Pictures(PTitle,PicturesByte) values(%s,%s)'
values = (PTitle, pictureByte)
try:
# execute SQL statement
cursor.execute(query, values)
# Submit to the database execution
con.commit()
print("\ 033 [37; 41M upload photos successfully \ 033 [0m")
except:
# As long as the execution is unsuccessful, roll back
con.rollback()
# download pictures to local
# ID: ID of the picture
# savepictureName: The preserved path defaults to the current directory
def downloadPicture(id, savePath=''):
# Take data from the database
query = 'SELECT PTitle,PicturesByte FROM Pictures where PId=%s'
values = (id)
# 19 19
cursor.execute(query, values)
titleAndPicture = cursor.fetchone() # Picture and title
pictureName = titleAndPicture[0] # Title
picture = titleAndPicture[1] # Picture
pictureFile = savePath + pictureName + '.png' # Picture path+file name+suffix
# Write binary data into pictures
writePicture = open(pictureFile, 'wb')
# Start writing data
writePicture.write(picture)
# Close and write
writePicture.close()
print("\ 033 [37; 41m download successfully! \ 033 [0m")
if __name__ == '__main__':
downloadPicture(2)
cursor.close()
conn.close()