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

数据库读取图片

 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)

 

posted @ 2022-05-25 10:52  葛老头  阅读(122)  评论(0编辑  收藏  举报