From 0ee9d840a108aeccd6a0492c9fe2a924179823c1 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Sat, 5 Sep 2020 18:51:33 +0100 Subject: [PATCH] Document context manager usage in connection and cursor docs Close #1143 --- doc/src/connection.rst | 22 ++++++++++++++++++++++ doc/src/cursor.rst | 10 ++++++++++ 2 files changed, 32 insertions(+) diff --git a/doc/src/connection.rst b/doc/src/connection.rst index ce69b591..05ad1404 100644 --- a/doc/src/connection.rst +++ b/doc/src/connection.rst @@ -21,6 +21,28 @@ The ``connection`` class Connections are thread safe and can be shared among many threads. See :ref:`thread-safety` for details. + Connections can be used as context managers. Note that a context wraps a + transaction: if the context exits with success the transaction is + committed, if it exits with an exception the transaction is rolled back. + Note that the connection is not closed by the context and it can be used + for several contexts. + + .. code:: python + + conn = psycopg2.connect(DSN) + + with conn: + with conn.cursor() as curs: + curs.execute(SQL1) + + with conn: + with conn.cursor() as curs: + curs.execute(SQL2) + + # leaving contexts doesn't close the connection + conn.close() + + .. method:: cursor(name=None, cursor_factory=None, scrollable=None, withhold=False) Return a new `cursor` object using the connection. diff --git a/doc/src/cursor.rst b/doc/src/cursor.rst index c6b04cf0..78db03f0 100644 --- a/doc/src/cursor.rst +++ b/doc/src/cursor.rst @@ -34,6 +34,16 @@ The ``cursor`` class many cursors from the same connection and should use each cursor from a single thread. See :ref:`thread-safety` for details. + Cursors can be used as context managers: leaving the context will close + the cursor. + + .. code:: python + + with conn.cursor() as curs: + curs.execute(SQL) + + # the cursor is now closed + .. attribute:: description