Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

python - Can two processes access in-memory (:memory:) sqlite database concurrently?

Is it possible to access database in one process, created in another? I tried:

IDLE #1

import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("create table test(testcolumn)")
c.execute("insert into test values('helloooo')")
conn.commit()
conn.close()

IDLE #2

import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("select * from test")

Error:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    q = c.execute("select * from test")
sqlite3.OperationalError: no such table: test
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, they cannot ever access the same in-memory database from different processes Instead, a new connection to :memory: always creates a new database.

From the SQLite documentation:

Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.

This is different from an on-disk database, where creating multiple connections with the same connection string means you are connecting to one database.

Within one process it is possible to share an in-memory database if you use the file::memory:?cache=shared URI:

conn = sqlite3.connect('file::memory:?cache=shared', uri=True)

but this is still not accessible from other another process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...