基于Python的上下文管理协议实现
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52import pymysql class Connect: def __enter__(self): self.conn = pymysql.connect( host='localhost', port=3306, # 连接的主机ip和端口 user='root', password='1234', # mysql用户,密码 db='stu', charset='utf8' # 连接的数据库,编码格式 ) self.cur = self.conn.cursor() return self def __exit__(self, exc_type, exc_val, exc_tb): # 函数结束完自动执行关闭连接 self.cur.close() self.conn.close() def find(sql): """ 无参数查询 """ with Connect() as db: # 打开Connect获取一个连接,执行完时自动关闭连接 db.cur.execute(sql) result = db.cur.fetchall() return result def find_para(sql, tup): # 传入元组 """ 有参数查询 """ with Connect() as db: db.cur.execute(sql, tup) result = db.cur.fetchall() return result def modify(sql): """ 无参增删改 """ with Connect() as db: db.cur.execute(sql) db.conn.commit() def modify_para(sql, tup): """ 有参增删改 """ with Connect() as db: db.cur.execute(sql, tup) db.conn.commit() # 调用封装方法示例 exc_sql = 'select * from user where userid=%s and username=%s' print(find_para(exc_sql, (201, "小黄")))
最后
以上就是不安溪流最近收集整理的关于Python封装MySql最优雅的方式基于Python的上下文管理协议实现的全部内容,更多相关Python封装MySql最优雅内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复