这个问题放了几天了好像也没有前辈解答, 我就自己回答一下吧, 解答方案可能存在错误, 也请前辈及时指出
1, 用with
文档里面说:
Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed:
大概就是说连接的数据库对象可以作为上下文管理器进行自动提交或者回滚, 所以代码大致如下:
conn = sqlite3.connect(data.sqlite)
sql = """xxxx"""
with conn:
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
当然也可以自己写一个上下文管理器, 如下:
class dbopen:
def __init__(self, path):
self.path = path
self.conn = None
self.cursor = None
def __enter__(self):
self.conn = sqlite3.connect(self.path)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_class, exc, traceback):
self.conn.commit()
self.conn.close()
with dbopen('data.sqlite') as cursor:
sql = """xxx"""
cursor.execute(sql)
print(cursor.fetchall())
2, 用装饰器
其实我不知道这个是不是一个好办法, 也很少看到有人这么做, 不过好像也可以用, 代码如下:
def dbconn(query):
def wrapper(cls, *args, **kwargs):
conn = sqlite3.connect(db_path)
result = query(cls, conn, *args, **kwargs)
conn.commit()
conn.close()
return result
return wrapper
class User:
@classmethod
@dbconn
def select_all(cls, conn):
cursor = conn.cursor()
sql = """xxx"""
cursor.execute(sql)
return cursor.fetchall()
Reference: