Search code examples
pythonsqlitewith-statement

Does Connection.__exit__ close itself in sqlite3?


I use to open SQL connections using with statements, like this

with sqlite3.connect('data.db') as con:
    # do something here

I supposed that a connection closes itself on an exit from the with block, just like files do, but now I have some doubts about this. I looked through Connection class documentation, but didn't find any clue. Does anybody know for sure what exactly Connection.__exit__ does? Thanks in advance!


Solution

  • No, it doesn't close the connection:

    # Connection object used as context manager only commits or rollbacks transactions,
    # so the connection object should be closed manually
    con.close()
    

    Using the connection as a context manager will commit or roll back.

    If you want to automatically close as well you could use the contextlib.closing context manager:

    from contextlib import closing
    
    with closing(sqlite3.connect('data.db')) as con:
        with con:
            # do something here
    

    You need the second with.