面向对象使用构造函数写数据库操作

import pymysql
from loguru import logger 打日志模块
import traceback 打印报错模块

MYSQL_INFO = {
'host':'118.24.3.40',
'user':'jxz',
'password':'123456',
'db':'jxz',
'charset':'utf8',
'autocommit':True
}
class MySQL:
def __init__(self,host,user,password,db,charset='utf8',autocommit=True):
self.conn = pymysql.connect(user=user,host=host,password=password,db=db,charset=charset,autocommit=autocommit)#连接游标
self.cursor = self.conn.cursor()


def __del__(self):
self.__close()

def execute(self,sql):
try:
self.cursor.execute(sql)
except Exception:
logger.error('sql执行出错,sql语句是{}',sql)
logger.error(traceback.format_exc())

def fetchall(self,sql):
self.execute(sql)
return self.cursor.fetchall()

def fetchone(self,sql):
self.execute(sql)
return self.cursor.fetchone()

def bak_db(self):
pass

def __close(self):
self.cursor.close()
self.conn.close()

if __name__ == '__main__':
my = MySQL(**MYSQL_INFO)
print(my.fetchall('select * from app_myuser;'))
my.fetchone('select * from app_myuser where id=1;')
my.fetchone('select * from app_myuser where id=1;')
my.fetchone('select * from app_myuser where id=1;')

这种定义的好处看着更清晰,这种和写一个tools文件封装数据库方法然后写函数调用对比的优点

posted @ 2021-03-15 10:15  测试董先生  阅读(119)  评论(0编辑  收藏  举报