What if I don't close the database connection in Python SQLite

后端 未结 6 2103
慢半拍i
慢半拍i 2020-11-30 00:55

I am doing something like this...

conn = sqlite3.connect(db_filename)

with conn:
    cur = conn.cursor()
    cur.execute( ... )

with

6条回答
  •  孤城傲影
    2020-11-30 01:49

    This is the code that I use. The Connection and the Cursor will automatically close thanks to contextlib.closing(). The Connection will automatically commit thanks to the context manager.

    import sqlite3
    import contextlib
    
    def execute_statement(statement):
        with contextlib.closing(sqlite3.connect(path_to_file)) as conn: # auto-closes
            with conn: # auto-commits
                with contextlib.closing(conn.cursor()) as cursor: # auto-closes
                    cursor.execute(statement)
    

提交回复
热议问题