Dao层编写
一、创建dao包,在__init__.py中编写代码:
import pymysql
from pymysql.cursors import DictCursor
CONFIG = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'root',
'db': 'bms',
'charset': 'utf8',
'cursorclass': DictCursor
}
class DB:
def __init__(self):
self.conn = pymysql.Connect(**CONFIG)
def __enter__(self):
print('__enter__')
return self.conn.cursor()
def __exit__(self, exc_type, exc_val, exc_tb):
print('__exit__')
if exc_type:
self.conn.rollback()
else:
self.conn.commit()
def close(self):
if self.conn:
self.conn.close()
self.conn = None
class BaseDao:
def __init__(self):
self.db = DB()
def find_all(self, table, where=None, *whereArgs):
sql = f"select * from {table}"
if where:
sql += where
with self.db as c:
c.execute(sql, whereArgs)
result = list(c.fetchall())
return result
二、在dao包中创建bank模块
from dao import BaseDao
class BankDao(BaseDao):
def find_all(self):
return super().find_all('python_test')
if __name__ == '__main__':
bankDao = BankDao()
result = bankDao.find_all()
print(result)