from pymysql import connect
class DBOpen(object):
# 初始化
def __init__(self, databasename):
# 创建Connection连接
self.conn = connect(host='localhost', port=3306, database=databasename, user='root', password='mysql',
charset='utf8')
# 获得Cursor对象
self.cs1 = self.conn.cursor()
# 返回操作符
def __enter__(self):
return self.cs1
# 退出
def __exit__(self, exc_type, exc_val, exc_tb):
# 关闭之前做一个统一的提交
self.conn.commit()
# 1.3 关闭
self.cs1.close()
self.conn.close()
with DBOpen("stock_db") as cs:
cs.execute("select * from info;")
data = cs.fetchall()
for temp in data:
print(temp)
mysql实现with上下文管理器----python
最新推荐文章于 2024-08-14 22:10:38 发布