python3存图片到数据库中并查询(附送一张张查看图片)
import sys
import pymysql
from PIL import Image
import os, time
path = "./"
# 打开图片存放到内存中
fp = open("./2.png", 'rb')
img = fp.read()
fp.close()
database = pymysql.connect(host="172.16.22.132", port=63306, user="root", passwd="sa",
db="wedora", charset='utf8mb4')
cursor = database.cursor()
#cursor.execute('ALTER TABLE photo CONVERT TO CHARACTER SET utf8mb4;')
#
i = 0
sql = "INSERT INTO photo(id, image) VALUES(%s, %s);"
img = str(img)
print(len(img))
print('----------------------')
# 图片存放到数据库
print(cursor.execute(sql, [i, img]))
database.commit()
print("Insert Done! ")
print("============")
print("Start Query ")
sql_query = "select image from photo;"
cursor.execute(sql_query)
for i in cursor.fetchall():
print(i)
print("共查询到:", cursor.rowcount, "条数据")
database.commit()
cursor.close()
database.close()
# 一张张显示图片
def show_images(directory):
for filename in os.listdir(directory):
path = directory + "/" + filename
im = Image.open(path)
im.show()
# os.system('pkill eog') # if you use GNOME Viewer
im.close()
#time.sleep(1)
show_images(r'D:\workspace\p_pymysql\pic')
本文来自博客园,作者:ReluStarry,转载请注明原文链接:https://www.cnblogs.com/relustarry/p/14381017.html