问题描述
是否可以在一个进程中访问数据库,而在另一个进程中创建?我试过了:
Is it possible to access database in one process, created in another?I tried:
空闲 #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()
空闲 #2
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("select * from test")
错误:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
q = c.execute("select * from test")
sqlite3.OperationalError: no such table: test
推荐答案
不,他们永远不能从不同的进程访问同一个内存数据库,而是一个新的连接到 :memory:
总是创建一个新数据库.
No, they cannot ever access the same in-memory database from different processes Instead, a new connection to :memory:
always creates a new database.
来自 SQLite 文档:
每个 :memory: 数据库都与众不同.因此,打开两个文件名为:memory:"的数据库连接将创建两个独立的内存数据库.
这与磁盘数据库不同,后者使用相同的连接字符串创建多个连接意味着您正在连接到一个数据库.
This is different from an on-disk database, where creating multiple connections with the same connection string means you are connecting to one database.
如果您使用file::memory:?cache=shared
URI,则可以在一个进程内共享内存数据库:
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.
这篇关于两个进程可以同时访问内存 (:memory:) sqlite 数据库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!