Is there a way to explicitly acquire a lock on a sqlite3 database in Python?
Is there a way to explicitly acquire a lock on a sqlite3 database in Python?
The way to explicitly lock the database is start a transaction as explained in the documentation:
When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed.
One way to initiate a transaction is use the connection as a context manager:
import sqlite3
con = sqlite3.connect(...)
...
with con:# Database is locked here
Also note that some transactions happen implictly by default:
By default, the sqlite3 module opens transactions implicitly before a Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly before a non-DML, non-query statement (i. e. anything other than SELECT or the aforementioned).