File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed
Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff 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
128149Attaching additional databases
Original file line number Diff line number Diff 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 ()
You can’t perform that action at this time.
0 commit comments