Suppose we have this code:
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的末尾打电话?
我认为,我的理解似乎自相矛盾的信息:
On one hand, this accepted answer says (with a link to SQLite3 source code): https://stackoverflow.com/a/25988110/9661990
不要担心关闭数据库。 当你要求准备或执行时,这些电话一旦发出,即自动停止。 有一个内部救助/检查组,确保即使出现错误,也关闭 d。 你们可以在Kalk3来源代码中看到这一点:数据库。
But on the other hand, this SQLite3 doc: https://docs.python.org/3/library/sqlite3.html
has a snippet with execute
, and yet in this snippet it specifically commands a manual 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()