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

2022/5/26 2:21:34

本文主要是介绍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)

 



这篇关于MySQL(12) - Python+MySQL读取写入图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程