Database can now work as a context manager, refs #692

This commit is contained in:
Simon Willison 2025-12-11 16:22:22 -08:00
commit f77ca0ec0d
2 changed files with 27 additions and 0 deletions

View file

@ -123,6 +123,27 @@ You can pass ``strict=True`` to enable `SQLite STRICT mode <https://www.sqlite.o
db = Database("my_database.db", strict=True)
.. _python_api_close:
Closing a database
------------------
Database objects maintain a connection to the underlying SQLite database. You can explicitly close this connection using the ``.close()`` method:
.. code-block:: python
db = Database("my_database.db")
# ... use the database ...
db.close()
The ``Database`` object also works as a context manager, which will automatically close the connection when the ``with`` block exits:
.. code-block:: python
with Database("my_database.db") as db:
db["my_table"].insert({"name": "Example"})
# Connection is automatically closed here
.. _python_api_attach:
Attaching additional databases

View file

@ -382,6 +382,12 @@ class Database:
pm.hook.prepare_connection(conn=self.conn)
self.strict = strict
def __enter__(self) -> "Database":
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.close()
def close(self) -> None:
"Close the SQLite connection, and the underlying database file"
self.conn.close()