mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-09-27 12:24:11 +02:00
Database can now work as a context manager, refs #692
This commit is contained in:
parent
066d0f3e8d
commit
f77ca0ec0d
2 changed files with 27 additions and 0 deletions
|
|
@ -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)
|
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:
|
.. _python_api_attach:
|
||||||
|
|
||||||
Attaching additional databases
|
Attaching additional databases
|
||||||
|
|
|
||||||
|
|
@ -382,6 +382,12 @@ class Database:
|
||||||
pm.hook.prepare_connection(conn=self.conn)
|
pm.hook.prepare_connection(conn=self.conn)
|
||||||
self.strict = strict
|
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:
|
def close(self) -> None:
|
||||||
"Close the SQLite connection, and the underlying database file"
|
"Close the SQLite connection, and the underlying database file"
|
||||||
self.conn.close()
|
self.conn.close()
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue