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

后端 未结 6 2086
慢半拍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:37

    You have a valid underlying concern here, however it's also important to understand how sqlite operates too:

    1. connection open
        2. transaction started
            3. statement executes
        4. transaction done
    5. connection closed
    

    in terms of data correctness, you only need to worry about transactions and not open handles. sqlite only holds a lock on a database inside a transaction(*) or statement execution.

    however in terms of resource management, e.g. if you plan to remove sqlite file or use so many connections you might run out of file descriptors, you do care about open out-of-transaction connections too.

    there are two ways a connection is closed: either you call .close() explicitly after which you still have a handle but can't use it, or you let the connection go out of scope and get garbage-collected.

    if you must close a connection, close it explicitly, according to Python's motto "explicit is better than implicit."

    if you are only checking code for side-effects, letting a last variable holding reference to connection go out of scope may be acceptable, but keep in mind that exceptions capture the stack, and thus references in that stack. if you pass exceptions around, connection lifetime may be extended arbitrarily.

    caveat programmator, sqlite uses "deferred" transactions by default, that is the transaction only starts when you execute a statement. In the example above, transaction runs from 3 to 4, rather than from 2 to 4.

提交回复
热议问题