4. 接口自动化框架---封装pymySQL(db_handler)

 1 import pymysql
 2 import settings
 3 
 4 
 5 class DB:
 6     def __init__(self, **kwargs):
 7         self.conn = pymysql.connect(**kwargs)
 8         self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
 9 
10     def exist(self, sql):
11         """
12         查询是否存在数据
13         :param sql: 需要执行的SQL
14         :return:
15         """
16         self.cursor.execute(sql)
17         if self.cursor.fetchone():
18             return True
19         return False
20 
21     def get_one(self, sql):
22         """
23         获取一条查询结果 -- fetchone
24         :param sql:
25         :return:
26         """
27         self.cursor.execute(sql)
28         return self.cursor.fetchone()
29 
30     def get_many(self, sql, num):
31         """
32         获取指定条数的查询结果 -- fetchmany
33         :param sql:
34         :param num: 指定条数(整数)
35         :return:
36         """
37         self.cursor.execute(sql)
38         return self.cursor.fetchmany(num)
39 
40     def get_all(self, sql):
41         """
42         获取所有的查询结果
43         :param sql:
44         :return:
45         """
46         self.cursor.execute(sql)
47         return self.cursor.fetchall()
48 
49     def get_count(self, sql):
50         """
51         获取查询数据的条数
52         :param sql:
53         :return:
54         """
55         return self.cursor.execute(sql)
56 
57     def __del__(self):
58         # 构析方法(删除操作)
59         self.cursor.close()
60         self.conn.close()
61 
62 
63 db = DB(**settings.DATABASE_CONFIG)
64 
65 if __name__ == '__main__':
66     db = DB(
67     host='数据库连接地址',
68     user='账号',
69     password='密码',
70     db='库名',
71     charset='utf8',
72     )
73 
74     res = db.get_one('select * from table order by id desc limit 1')
75     print(res)
76     res = db.exist("select id from table where mobile_phone='10086'")
77     print(res)
78     res = db.cursor.execute('sql')
79     print(res)
80     print(db.cursor.fetchone())

 

posted @ 2022-03-21 13:12  WJ-HAHA  阅读(84)  评论(0编辑  收藏  举报