您的位置:首页 > 编程语言 > Python开发

MySQL(12) - Python+MySQL读取写入图片

2022-05-25 10:52 2763 查看

数据库读取图片

import mysql.connector.pooling
import os

__config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '123456',
'database': 'test'
}

try:
pool = mysql.connector.pooling.MySQLConnectionPool(
**__config,
pool_size=10
)
except Exception as e:
print(e)

def save_image_dao(name, image):
try:
con = pool.get_connection()
con.start_transaction()
cursor = con.cursor()
sql = 'INSERT INTO t_image(name,image) ' \
'VALUES(%s,%s)'
cursor.execute(sql, (name, image))
con.commit()
except Exception as e:
if 'con' in dir():
con.rollback()
print(e)
finally:
if 'con' in dir():
con.close()

def read_image_dao(name):
try:
con = pool.get_connection()
cursor = con.cursor()
sql = 'SELECT image FROM t_image ' \
'WHERE name=%s'
cursor.execute(sql, [name])
result = cursor.fetchone()
if result:
image = result[0]
return image
except Exception as e:
print(e)
finally:
if 'con' in dir():
con.close()

def save_image(file_name, dir_path):
path = os.path.join(dir_path, file_name)
try:
with open(path, 'rb') as f:
image = f.read()
save_image_dao(file_name, image)
except Exception as e:
print(e)

def read_image(image_name, file_name, dir_path):
path = os.path.join(dir_path, file_name)
try:
image = read_image_dao(image_name)
with open(path, 'wb+') as f:
f.write(image)
except Exception as e:
print(e)

if __name__ == '__main__':
file_name = 'test.jpg'
dir_path = os.getcwd()
save_image(file_name, dir_path)
new_file_name = 'test_new.jpg'
read_image(file_name, new_file_name, dir_path)

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: