假设我们有这个代码:
def _te(tn: str, db_id: str) -> bool:
with _connect_db(db_id) as conn:
cur = conn.cursor()
cur.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", (tn,))
return cur.fetchone()[0] == 1
def _connect_db(db_id: str) -> sqlite3.Connection:
return sqlite3.connect(db_id)
我需要在
_te
结束时调用close吗?
我发现在我的理解水平上似乎矛盾的信息:
一方面,这个已接受的答案说(带有 SQLite3 源代码的链接): https://stackoverflow.com/a/25988110/9661990
您无需担心关闭数据库。当您调用准备或执行时,这些调用在完成后会自动调用关闭。有一个内部救援/确保块可以确保数据库关闭,即使出现错误也是如此。您可以在 SQLite3::Database 的源代码中看到这一点。
但另一方面,这个 SQLite3 文档: https://docs.python.org/3/library/sqlite3.html
有一个带有
execute
的片段,但在这个片段中它专门命令一个手册 close
:
# Create and fill the table.
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE lang(name, first_appeared)")
data = [
("C++", 1985),
("Objective-C", 1984),
]
con.executemany("INSERT INTO lang(name, first_appeared) VALUES(?, ?)", data)
# Print the table contents
for row in con.execute("SELECT name, first_appeared FROM lang"):
print(row)
print("I just deleted", con.execute("DELETE FROM lang").rowcount, "rows")
# close() is not a shortcut method and it's not called automatically;
# the connection object should be closed manually
con.close()
正如您已经在做的那样,上下文管理器将为您处理这个问题。
import sqlite3
def _te(tn: str, db_id: str) -> bool:
with sqlite3.connect(db_id) as conn:
cur = conn.cursor()
cur.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", (tn,))
return cur.fetchone()[0] == 1
with sqlite3.connect(db_id) as conn:
语句确保当with语句中的代码块退出时或函数调用结束时数据库连接自动关闭。
在文档中,为了透明起见,示例通常用
.close()
编写。