Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sqlite3 and concurrency

Tags:

python

sqlite

I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:

conn = sqlite3.connect("mydatabase.db") 
  • If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.
  • If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.

Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?

like image 361
RexE Avatar asked Dec 26 '08 06:12

RexE


People also ask

Does SQLite3 support concurrency?

Usually, SQLite allows at most one writer to proceed concurrently. The BEGIN CONCURRENT enhancement allows multiple writers to process write transactions simultanously if the database is in "wal" or "wal2" mode, although the system still serializes COMMIT commands.

Is SQLite3 thread safe Python?

Is it safe to share an sqlite3 connection between threads? Yes, unless you change the default THREADSAFE option.

How many concurrent connections can SQLite handle?

The default limit is 1,024.

Does SQLite support multiprocessing?

and to add to that, sqlite works fine in a multi-process environment, as long as your aware that locking may cause some calls to time-out (fail), and that they then need to be re-tried. I know the thread/process -difference, and i use multiple processes (multiprocessing module with pools).


1 Answers

Contrary to popular belief, newer versions of sqlite3 do support access from multiple threads.

This can be enabled via optional keyword argument check_same_thread:

sqlite.connect(":memory:", check_same_thread=False) 
like image 111
Jeremiah Rose Avatar answered Oct 20 '22 01:10

Jeremiah Rose