在Python sqlite3中,上下文管理器
with sqlite3.connect(database)
将自动提交或回滚事务。但是,它不会关闭连接也不会关闭游标。所以每次我都要写这样的东西:
with sqlite3.connect(database) as conn:
cur = conn.cursor()
cur.execute(an_sql_statement)
cur.executemany(more_sql_statements)
cur.close()
conn.close()
这很重复。
我希望能够做这样的事情:
with AutoCloseDB(database) as cur:
cur.execute(an_sql_statement)
cur.executemany(more_sql_statements)
并且上述上下文管理器将自动提交或回滚事务,在退出时关闭游标并最终完全关闭数据库。
所以我想出了以下上下文管理器:
import sqlite3
class AutoCloseDB:
"""A context manager that automatically closes the cursor and the database.
Return a cursor object upon entering.
"""
def __init__(self, database):
self.conn = sqlite3.connect(database)
def __enter__(self):
self.conn = self.conn.__enter__()
self.cur = self.conn.cursor()
return self.cur
def __exit__(self, *exc_info):
result = self.conn.__exit__(*exc_info)
self.cur.close()
self.conn.close()
return result
以上代码是否有问题?有更好的解决方案吗?