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

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

    You can use a with block like this:

    from contextlib import closing
    import sqlite3
    
    def query(self, db_name, sql):
        with closing(sqlite3.connect(db_name)) as con, con,  \
                closing(con.cursor()) as cur:
            cur.execute(sql)
            return cur.fetchall()
    
    • connects
    • starts a transaction
    • creates a db cursor
    • preforms the operation and returns the results
    • closes the cursor
    • commits/rolls-back the transaction
    • closes the connection

    all safe in both happy and exceptional cases

提交回复
热议问题