上代码
注意__enter__函数必须返回创建的对象,用于with体调用
__exit__即使with体内报错,也会执行
class openmysql():
def __init__(self,*args,**kwargs):
"""
kwargs like host='www', user='root', passwd='123456', db='test', port=3306
"""
####将传进来的变量保存到self,不能在这个函数进行conn的创建
####因为初始化变量后不一定会执行变量的__exit__,容易造成僵尸连接
for k,v in kwargs.items():
setattr(self,k,v)
def __enter__(self):
try:
import pymysql
except Exception:
raise Exception('pymysql must be installed at your environment')
self.conn = pymysql.connect(**self.__dict__)
self.cursor = self.conn.cursor()
return self
def execute(self,sql):
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
self.conn.close()
del self
####试用一下
mysql_config = dict(host='localhost', user='admin', passwd='123456', db='game', port=3307)
with openmysql(**mysql_config) as mysqlc:
re = mysqlc.execute('select * from game.activities;')
print(re)