Python SQLite: database is locked

后端 未结 20 1157
一生所求
一生所求 2020-12-12 14:24

I\'m trying this code:

import sqlite

connection = sqlite.connect(\'cache.db\')
cur = connection.cursor()
cur.execute(\'\'\'create table item
  (id integer p         


        
20条回答
  •  -上瘾入骨i
    2020-12-12 15:04

    I had the same problem: sqlite3.IntegrityError

    As mentioned in many answers, the problem is that a connection has not been properly closed.

    In my case I had try except blocks. I was accessing the database in the try block and when an exception was raised I wanted to do something else in the except block.

    try:
        conn = sqlite3.connect(path)
        cur = conn.cursor()
        cur.execute('''INSERT INTO ...''')
    except:
        conn = sqlite3.connect(path)
        cur = conn.cursor()
        cur.execute('''DELETE FROM ...''')
        cur.execute('''INSERT INTO ...''')
    

    However, when the exception was being raised the connection from the try block had not been closed.

    I solved it using with statements inside the blocks.

    try:
        with sqlite3.connect(path) as conn:
            cur = conn.cursor()
            cur.execute('''INSERT INTO ...''')
    except:
        with sqlite3.connect(path) as conn:
            cur = conn.cursor()
            cur.execute('''DELETE FROM ...''')
            cur.execute('''INSERT INTO ...''')
    

提交回复
热议问题