-
Notifications
You must be signed in to change notification settings - Fork 17
Description
# The with statement is helpful, because it ensures that the connection
# is closed at the end, even if an exception occurs
with sqlite3.connect("../db/lesson.db") as conn:
conn.execute("PRAGMA foreign_keys = 1") This is incorrect. https://docs.python.org/3/library/sqlite3.html#sqlite3-connection-context-manager
A Connection object can be used as a context manager that automatically commits or rolls back open transactions when leaving the body of the context manager. If the body of the with statement finishes without exceptions, the transaction is committed. If this commit fails, or if the body of the with statement raises an uncaught exception, the transaction is rolled back. If autocommit is False, a new transaction is implicitly opened after committing or rolling back.
If there is no open transaction upon leaving the body of the with statement, or if autocommit is True, the context manager does nothing.
Note The context manager neither implicitly opens a new transaction nor closes the connection. If you need a closing context manager, consider using contextlib.closing().
Example:
import sqlite3
with sqlite3.connect("../db/magazines.db") as conn:
...
print(conn.execute("SELECT 1").fetchone())
conn.close()
print(conn.execute("SELECT 1").fetchone())
> (1,)
> sqlite3.ProgrammingError: Cannot operate on a closed database.There may be other files with the same practice.