Added documentation for the with statement

This commit is contained in:
Daniele Varrazzo 2012-12-03 03:18:51 +00:00
parent cc605032f5
commit c2f284cd3b
3 changed files with 37 additions and 0 deletions

View File

@ -74,6 +74,10 @@ The ``connection`` class
automatically open, commands have immediate effect. See
:ref:`transactions-control` for details.
.. versionchanged:: 2.5 if the connection is used in a ``with``
statement, the method is automatically called if no exception is
raised in the ``with`` block.
.. index::
pair: Transaction; Rollback
@ -84,6 +88,10 @@ The ``connection`` class
connection without committing the changes first will cause an implicit
rollback to be performed.
.. versionchanged:: 2.5 if the connection is used in a ``with``
statement, the method is automatically called if an exception is
raised in the ``with`` block.
.. method:: close()

View File

@ -84,6 +84,11 @@ The ``cursor`` class
`~psycopg2.InterfaceError` will be raised if any operation is
attempted with the cursor.
.. versionchanged:: 2.5 if the cursor is used in a ``with`` statement,
the method is automatically called at the end of the ``with``
block.
.. attribute:: closed
Read-only boolean attribute: specifies if the cursor is closed

View File

@ -548,6 +548,30 @@ change the isolation level. See the `~connection.set_session()` method for all
the details.
.. index::
single: with statement
``with`` statement
^^^^^^^^^^^^^^^^^^
Starting from version 2.5, psycopg2's connections and cursors are *context
managers* and can be used with the ``with`` statement::
with psycopg2.connect(DSN) as conn:
with conn.cursor() as curs:
curs.execute(SQL)
When a connection exits the ``with`` block, if no exception has been raised by
the block, the transaction is committed. In case of exception the transaction
is rolled back. In no case the connection is closed: a connection can be used
in more than a ``with`` statement and each ``with`` block is effectively
wrapped in a transaction.
When a cursor exits the ``with`` block it is closed, releasing any resource
eventually associated with it. The state of the transaction is not affected.
.. index::
pair: Server side; Cursor
pair: Named; Cursor