Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock a sqlite3 database in Python?

Tags:

python

sqlite

Is there a way to explicitly acquire a lock on a sqlite3 database in Python?

like image 595
Stephen Gross Avatar asked Jan 12 '12 00:01

Stephen Gross


People also ask

Does SQLite lock database?

SQLite Lock UsageBegins the transaction, locking the entire database for reading. Use this if you only want to read from the database. Begins the transaction, acquiring a "modify" lock. This is also known as a RESERVED lock.

Is sqlite3 thread safe Python?

In this mode, SQLite can be safely used by multiple threads provided that no single database connection is used simultaneously in two or more threads. Serialized. In serialized mode, SQLite can be safely used by multiple threads with no restriction.


2 Answers

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).

like image 50
jcollado Avatar answered Sep 28 '22 10:09

jcollado


From the sqlite FAQ, "Can multiple applications or multiple instances of the same application access a single database file at the same time?":

Multiple processes can have the same database open at the same time. Multiple processes can be doing a SELECT at the same time. But only one process can be making changes to the database at any moment in time, however.

Whether or not you use the with connection construct, many processes can read from by only one can write to the database at any given time.

like image 24
unutbu Avatar answered Sep 28 '22 09:09

unutbu