Feature Request: Using pyodbc as context managers

86 views
Skip to first unread message

GotGTKWantWx

unread,
Jun 1, 2010, 11:07:11 AM6/1/10
to pyodbc
I would like to propose adding support to pyodbc to enable its use as
a context manager. That is, I would like the following to work:

import pyodbc
with pyodbc.connect (dsn='mydb') as conn:
with conn.cursor() as curs:
with curs.execute('select * from mytable) as selected:
for row in selected:
#do something useful

This will mean adding __enter__ and __exit__ methods to these
objects. I propose that __enter__ just return the object and __exit__
do something like:

1. for pyodbc.connect -- automatically close the connection
2. for cursor objects -- automatically commit (unless autocommit=false
in connect) and close the cursor
3. for execute -- not sure yet (maybe not as useful)

amand...@gmail.com

unread,
Sep 22, 2012, 10:49:08 PM9/22/12
to pyo...@googlegroups.com
I came across this post while checking to see if pyodbc was possible to use with "with" statements. +1 on this feature :)

Michael Kleehammer

unread,
Sep 26, 2012, 5:54:43 PM9/26/12
to pyo...@googlegroups.com
This has been checked in, so if you are building from source you can try it today.

I'll try to cut 3.0.7 with this ASAP.

Reply all
Reply to author
Forward
0 new messages