Should I call connect() and close() for every Sqlite3 transaction?

泪湿孤枕 提交于 2021-02-04 16:31:20

问题


I want to write a Python module to abstract away database transactions for my application. My question is whether I need to call connect() and close() for every transaction? In code:

import sqlite3

# Can I put connect() here?
conn = sqlite3.connect('db.py')

def insert(args):
    # Or should I put it here?
    conn = sqlite3.connect('db.py')
    # Perform the transaction.
    c = conn.cursor()
    c.execute(''' insert args ''')
    conn.commit()
    # Do I close the connection here?
    conn.close()

# Or can I close the connection whenever the application restarts (ideally, very rarely)
conn.close()

I have don't much experience with databases, so I'd appreciate an explanation for why one method is preferred over the other.


回答1:


You can use the same connection repeatedly. You can also use the connection (and the cursor) as a context manager so that you don't need to explicitly call close on either.

def insert(conn, args):
    with conn.cursor() as c:
        c.execute(...)
    conn.commit()

with connect('db.py') as conn:
    insert(conn, ...)
    insert(conn, ...)
    insert(conn, ...)

There's no reason to close the connection to the database, and re-opening the connection each time can be expensive. (For example, you may need to establish a TCP session to connect to a remote database.)




回答2:


Using a single connection will be faster, and operationally should be fine.

Use the atexit module if you want to ensure the closing eventually happens (even if your program is terminated by an exception). Specifically, import atexit at the start of your program, and atexit.register(conn.close) right after you connect -- note, no () after close, you want to register the function to be called at program exist (whether normal or via an exception), not to call the function.

Unfortunately if Python should crash due e.g to an error in a C-coded module that Python can't catch, or a kill -9, etc, the registered exit function(s) may end up not being called. Fortunately in this case it shouldn't hurt anyway (besides being, one hopes, a rare and extreme occurrence).



来源:https://stackoverflow.com/questions/27829010/should-i-call-connect-and-close-for-every-sqlite3-transaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!