Python實現將圖片以二進制格式保存到MySQL數據庫中,以及取出:


創建數據庫表格式:

CREATE TABLE photo ( photo_no int(6) unsigned NOT NULL auto_increment, image MEDIUMBLOB, PRIMARY KEY (`photo_no`) );

Python實現將圖片以二進制格式保存到MySQL數據庫中:

import sys
import pymysql
from PIL import Image
import os
 
path = "./"

fp = open("./1.png", 'rb')
img = fp.read()
fp.close()

database = pymysql.connect(host="localhost", user="root", passwd="", db="hua")
cursor = database.cursor()
sql = "INSERT INTO photo (image) VALUES  (%s);"
args = (img)
cursor.execute(sql, args)
database.commit()
cursor.close()
database.close()

print("============")
print("Done! ")

Python實現從MySQL數據庫中將二進制格式的圖片保存到本地:

import pymysql as mdb
import sys

conn = mdb.connect(host='localhost',user='root',passwd='',db='hua')
cursor = conn.cursor()
cursor.execute("SELECT image FROM photo LIMIT 1")
fout = open('quchu1.png','wb')
fout.write(cursor.fetchone()[0])
fout.close()
cursor.close()
conn.close()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM