我应该为每个Sqlite3事务调用connect()和close()吗?

时间:2015-01-07 21:31:55

标签: python sqlite

我想编写一个Python模块来抽象出我的应用程序的数据库事务。我的问题是,是否需要为每笔交易致电connect()close()?在代码中:

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()

我对数据库的经验不多,所以我很感激为什么一种方法优先于另一种方法的解释。

2 个答案:

答案 0 :(得分:5)

您可以重复使用相同的连接。您还可以使用连接(和光标)作为上下文管理器,这样就不需要在任何一个上显式调用close

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, ...)

没有理由关闭与数据库的连接,每次重新打开连接都很昂贵。 (例如,您可能需要建立TCP会话以连接到远程数据库。)

答案 1 :(得分:1)

使用单个连接会更快,操作上也应该没问题。

如果要确保最终结束(即使您的程序因例外而终止),请使用atexit模块。具体而言,您的计划开始时为import atexitatexit.register(conn.close)之后为connect - 请注意()之后 close },你想要注册在程序中调用的函数(无论是正常的还是通过异常),调用该函数。

不幸的是,如果Python由于Python无法捕获的C编码模块中的错误或kill -9等而导致崩溃,则注册的退出函数可能最终不会调用。幸运的是,在这种情况下它无论如何都不应该受到伤害(除了存在,一种希望,一种罕见的极端事件)。