pythondatabasesqlitewith-statement

Is there a "with conn.cursor() as..." way to work with Sqlite?


Instead of using:

import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute(...)
c.close()

would it be possible to use the Pythonic idiom:

with conn.cursor() as c:
    c.execute(...)

It doesn't seem to work:

AttributeError: __exit__

Note: it's important to close a cursor because of this.


Solution

  • You can use contextlib.closing:

    import sqlite3
    from contextlib import closing
    
    conn = sqlite3.connect(':memory:')
    
    with closing(conn.cursor()) as cursor:
        cursor.execute(...)
    

    This works because closing(object) automatically calls the close() method of the passed in object after the with block.