I\'m trying this code:
import sqlite
connection = sqlite.connect(\'cache.db\')
cur = connection.cursor()
cur.execute(\'\'\'create table item
(id integer p
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 ...''')