HandleDB.py
1.82 KB
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
# @Time : 2022/8/30 16:28
# @Author : 付孟奇
from config.VendorPath import base_path
from util.HandleFile import load_ini_file
from util.HandleLog import logger
import os
import pymysql
db_file_path = os.path.join(base_path, 'config', 'db.ini')
class DBLoad:
def __init__(self):
db_res = load_ini_file(db_file_path, 'mysql')
self.DB_CONF = {
'host': db_res['mysql_host'],
'port': int(db_res['mysql_port']),
'user': db_res['mysql_user'],
'passwd': db_res['mysql_passwd'],
'db': db_res['mysql_db'],
}
self.connect()
def connect(self, db_conf=None):
# 通过字典拆包传递配置信息,建立数据库连接
if db_conf is None:
db_conf = self.DB_CONF
self.conn = pymysql.connect(**db_conf, autocommit=True)
# 通过 cursor() 创建游标对象,并让查询结果以字典格式输出
self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
def select_db(self, sql):
"""查询"""
# 检查连接是否断开,如果断开就进行重连
self.conn.ping(reconnect=True)
# 使用 execute() 执行sql
self.cur.execute(sql)
# 使用 fetchall() 获取查询结果
data = self.cur.fetchall()
return data
def execute_db(self, sql):
"""更新/新增/删除"""
try:
# 检查连接是否断开,如果断开就进行重连
self.conn.ping(reconnect=True)
# 使用 execute() 执行sql
self.cur.execute(sql)
# 提交事务
self.conn.commit()
except Exception as e:
logger.info("操作MySQL出现错误,错误原因:{}".format(e))
# 回滚所有更改
self.conn.rollback()
db_load = DBLoad()