Skip to content

Commit f77ca0e

Browse files
committed
Database can now work as a context manager, refs #692
1 parent 066d0f3 commit f77ca0e

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

docs/python-api.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,27 @@ You can pass ``strict=True`` to enable `SQLite STRICT mode <https://www.sqlite.o
123123
124124
db = Database("my_database.db", strict=True)
125125
126+
.. _python_api_close:
127+
128+
Closing a database
129+
------------------
130+
131+
Database objects maintain a connection to the underlying SQLite database. You can explicitly close this connection using the ``.close()`` method:
132+
133+
.. code-block:: python
134+
135+
db = Database("my_database.db")
136+
# ... use the database ...
137+
db.close()
138+
139+
The ``Database`` object also works as a context manager, which will automatically close the connection when the ``with`` block exits:
140+
141+
.. code-block:: python
142+
143+
with Database("my_database.db") as db:
144+
db["my_table"].insert({"name": "Example"})
145+
# Connection is automatically closed here
146+
126147
.. _python_api_attach:
127148

128149
Attaching additional databases

sqlite_utils/db.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,12 @@ def __init__(
382382
pm.hook.prepare_connection(conn=self.conn)
383383
self.strict = strict
384384

385+
def __enter__(self) -> "Database":
386+
return self
387+
388+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
389+
self.close()
390+
385391
def close(self) -> None:
386392
"Close the SQLite connection, and the underlying database file"
387393
self.conn.close()

0 commit comments

Comments
 (0)