from pymysql import connect
class OpenDB(object):
def __init__(self, user, pw, database):
# 初始化
self.conn = connect(host='localhost', port=3306, user=user, password=pw, database=database, charset='utf8')
self.cs = self.conn.cursor()
def __enter__(self):
# 返回游标进行执行操作
return self.cs
def __exit__(self, exc_type, exc_val, exc_tb):
# 结束提交数据并关闭数据库
self.conn.commit()
self.cs.close()
self.conn.close()
###########################使用前导入以上模块#################################
with OpenDB('用户名', '密码', '库名') as f:
sql = """写入SQL语句"""
# 执行sql语句
f.execute(sql)
# 获取数据
content = f.fetchall()
for temp in content:
print(temp)
python中使用with打开数据库
最新推荐文章于 2023-03-01 10:42:04 发布