[DB-SIG] Context manager support for cursors

Daniele Varrazzo daniele.varrazzo at gmail.com
Thu Jul 26 07:56:55 EDT 2018

On Thu, Jul 26, 2018 at 4:30 AM, Daniel Lenski <dlenski at gmail.com> wrote:
> On Tue, Jul 24, 2018 at 12:37 AM, Federico Di Gregorio <fog at dndg.it> wrote:
>> On 06/21/2018 01:31 AM, Gerald Venzl wrote:
>>> Hi all,
>>> I was wondering whether there has been any particular reason that the
>>> specification of the Cursor object doesn’t implement a context manager to
>>> enable for example the “with” statement?
>>> Being able to use the “with” statement for database cursors, just like
>>> other external resources like files, etc., I think makes a lot of sense:
>>> with conn.cursor()as c:
>>>      c.execute("SELECT 'test' from dual")
>>>      result = c.fetchall()
>>>      print(result)
>> It does (make sense). The explanation is that context managers did not exist
>> when the PEP was written. An update is long overdue, IMHO.

In 2012 the thing was discussed

The most used semantics appears what documented here:


but it hasn't made it into the specs so far.

Note: while the assumption is that cursors are closed at the end of
the block, this is not true for connection, for which the most useful
thing is to commit or roll back the transaction. Or at least the most
useful if the connection is not autocommit).

> Python Database API Specification v3.0, anyone…? :-P

In case there would be work in its direction, points to touch, on top
of my mind (implemented in various way by different drivers) are also

- unicode support
- Python 3 support (likely it will be the only targeted version)
- async support
- multiprocess support
- green threads support
- autocommit (was not-autocommit by default a good idea, even?)
- should execute(query) with no param go for a round of placeholders
escape on the string as it would execute(query, {})?
- placeholders style, of course...

-- Daniele

More information about the DB-SIG mailing list