当前位置:首页 > 数据库 > SQlite

python – 两个进程可以同时访问内存(:memory :) sqlite数据库吗?

是否可以在一个进程中访问数据库,在另一个进程中创建?
我试过了:

空闲#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")

错误:

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:总是创建一个新的数据库.

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.

这与磁盘数据库不同,在磁盘数据库中,使用相同的连接字符串创建多个连接意味着您将连接到一个数据库.

在一个进程中,如果使用文件:: memory:?cache = shared URI,则可以共享内存数据库:

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

但这仍然无法通过其他流程访问.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!