I have written a script that executes inside docker and writes to an sqlite3 db on host. At a time, there are 8-10 such docker containers writing to the same database (each having their own connection).
In my script, I create an sqlite connection and get a cursor and use it for the lifecycle of the whole program (multiple cur.execute(), con.commit(), con.rollback()). I initiate the connection with 20 second timeout:
con = sqlite3.connect('database.db', timeout=20)
but I still get sqlite3: database is locked.
errors.
I have tried this solution like this:
while True:
try:
cur.execute(f"...insert into db statement...")
break
except sqlite3.OperationalError:
continue
and similarly for con.commit()
and con.rollback()
in place of cur.execute()
.
My question is, is there a better way to do this? I am not checking if the while loop for any of the containers is stuck in infinite loop. I have seen answers creating connection and cursor inside and cursor inside the while loop, does creating a connection lock the database? does cur.execute() lock it or only con.commit()?