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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
| # 先要导入pymysql
| import logging
|
| import pymysql
|
| # 把连接参数定义成字典
| import constant
|
| config = constant.MYSQL_CONFIG
|
| class Mysqldb:
| # 初始化方法
| def __init__(self):
| # 初始化方法中调用连接数据库的方法
| self.conn = self.get_conn()
| # 调用获取游标的方法
| self.cursor = self.get_cursor()
|
| def close(self):
| self.conn.close()
|
| # 连接数据库的方法
| def get_conn(self):
| # **config代表不定长参数
| conn = pymysql.connect(**config)
| return conn
|
| # 获取游标
| def get_cursor(self):
| cursor = self.conn.cursor()
| return cursor
|
| # 查询sql语句返回的所有数据
| def select_all(self, sql):
| self.cursor.execute(sql)
| return self.cursor.fetchall()
|
| # 查询sql语句返回的一条数据
| def select_one(self, sql):
| self.cursor.execute(sql)
| return self.cursor.fetchone()
|
| # 查询sql语句返回的几条数据
| def select_many(self, sql, num):
| self.cursor.execute(sql)
| return self.cursor.fetchmany(num)
|
| # 增删改除了SQL语句不一样其他都是一样的,都需要提交
| def execute(self, sql, args=None):
| try:
| # 执行语句
| self.cursor.execute(sql, args)
| # 提交
| self.conn.commit()
| except Exception as e:
| print("提交出错\n:", e)
| logging.exception(e)
| # 如果出错要回滚
| self.conn.rollback()
|
| def execute_many(self, sql, args=None):
| try:
| # 执行语句
| self.cursor.executemany(sql, args)
| # 提交
| self.conn.commit()
| except Exception as e:
| logging.exception(e)
| print("提交出错\n:", e)
| # 如果出错要回滚
| self.conn.rollback()
|
| # 当对象被销毁时,游标要关闭,连接也要关闭
| # 创建时是先创建连接后创建游标,关闭时是先关闭游标后关闭连接
| def __del__(self):
| self.cursor.close()
| self.conn.close()
|
|
| if __name__ == '__main__':
| mysqldb = Mysqldb()
| # 插入单条数据
| mysqldb.execute("insert into clients(account,pwd,rule) values(%s,%s,%s)", ("test", 123456, "\"123"))
| # 插入多条数据
| mysqldb.execute_many("insert into clients(account,pwd,rule) values(%s,%s,%s)", [("test", 123456, "\"123"),("test", 123456, "\"123")])
|
|