import pymysql
class MysqlDB:
def __init__(self, data_conf):
self.connect = pymysql.connect(**data_conf)
self.cursor = self.connect.cursor()
def __enter__(self):
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
self.connect.close()
DATABASE_CONF = dict(
host='localhost',
port=3306,
user='root',
password='root',
database='dbname',
charset='utf-8'
)
with MysqlDB(DATABASE_CONF) as cursor:
cursor.execute('sql')
数据库上下文管理器
最新推荐文章于 2023-11-11 13:57:47 发布