ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2022-05-25 11:02:20  阅读:168  来源: 互联网

标签:12 name Python image file MySQL path dir con


数据库读取图片

 1 import mysql.connector.pooling
 2 import os
 3 
 4 __config = {
 5     'host': 'localhost',
 6     'port': 3306,
 7     'user': 'root',
 8     'password': '123456',
 9     'database': 'test'
10 }
11 
12 try:
13     pool = mysql.connector.pooling.MySQLConnectionPool(
14         **__config,
15         pool_size=10
16     )
17 except Exception as e:
18     print(e)
19 
20 def save_image_dao(name, image):
21     try:
22         con = pool.get_connection()
23         con.start_transaction()
24         cursor = con.cursor()
25         sql = 'INSERT INTO t_image(name,image) ' \
26               'VALUES(%s,%s)'
27         cursor.execute(sql, (name, image))
28         con.commit()
29     except Exception as e:
30         if 'con' in dir():
31             con.rollback()
32         print(e)
33     finally:
34         if 'con' in dir():
35             con.close()
36 
37 def read_image_dao(name):
38     try:
39         con = pool.get_connection()
40         cursor = con.cursor()
41         sql = 'SELECT image FROM t_image ' \
42               'WHERE name=%s'
43         cursor.execute(sql, [name])
44         result = cursor.fetchone()
45         if result:
46             image = result[0]
47             return image
48     except Exception as e:
49         print(e)
50     finally:
51         if 'con' in dir():
52             con.close()
53 
54 def save_image(file_name, dir_path):
55     path = os.path.join(dir_path, file_name)
56     try:
57         with open(path, 'rb') as f:
58             image = f.read()
59         save_image_dao(file_name, image)
60     except Exception as e:
61         print(e)
62 
63 def read_image(image_name, file_name, dir_path):
64     path = os.path.join(dir_path, file_name)
65     try:
66         image = read_image_dao(image_name)
67         with open(path, 'wb+') as f:
68             f.write(image)
69     except Exception as e:
70         print(e)
71 
72 if __name__ == '__main__':
73     file_name = 'test.jpg'
74     dir_path = os.getcwd()
75     save_image(file_name, dir_path)
76     new_file_name = 'test_new.jpg'
77     read_image(file_name, new_file_name, dir_path)

 

标签:12,name,Python,image,file,MySQL,path,dir,con
来源: https://www.cnblogs.com/gltou/p/16201805.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有