I would like to create a :memory: database in python and access it from different threads. Essentially something like:
class T(threading.Thread):
def run(self):
self.conn = sqlite3.connect(':memory:')
# do stuff with the database
for i in xrange(N):
T().start()
and have all the connections referring to the same database.
I am aware of passing check_same_thread=True
to the connect function and sharing the
connection between threads but would like to avoid doing that if possible. Thanks for any help.
EDIT: corrected a typo. I originally said "have all the connections referring to the same thread" substituting thread for database.
Without hacking sqlite3 library itself you cannot reuse
:memory:
database, because it's guaranteed to be exclusive and private for every connection. To hack access to it, look closer atsrc/pager.c
in sqlite3 distribution (not Python module distribution). Maybe, most convenient way to implement this would be make:memory:00
,:memory:something
,:memory:okay_hai
etc. aliases to address differentpPager->memDb
pointers through some simple C-side mapping.SQLite had improved over last 4 years, so now shared in-memory databases are possible. Check the following code:
Database accesses are entangled intentionally, to show that two connections to the in-memory database with the same name are the same from SQLite's point of view.
References:
Unfortunately, connection by URI is only available since Python 3.4. However, if you have Python 2.6 or later (but not Python 3), builtin
sqlite3
module is still capable of importing APSW connections, which can be used to achieve same effect. Here goes the drop-insqlite3
module replacement: