【问题标题】:Multiple SQLite connections to a database in :memory:多个 SQLite 连接到 :memory 中的数据库:
【发布时间】:2016-07-26 15:46:54
【问题描述】:

是否可以从不同的线程访问内存中的 SQLite 数据库?

在下面的示例代码中,我在内存中创建了一个 SQLite 数据库并创建了一个表。当我现在转到不同的执行上下文时,我认为当我转到不同的线程时必须这样做,创建的表不再存在。如果我打开一个基于文件的 SQLite 数据库,表就会在那里。

我可以为内存数据库实现相同的行为吗?

from peewee import *
db = SqliteDatabase(':memory:')

class BaseModel(Model):
    class Meta:
        database = db

class Names(BaseModel):
    name = CharField(unique=True)

print(Names.table_exists())  # this returns False 
Names.create_table()
print(Names.table_exists())  # this returns True

print id(db.get_conn())  # Our main thread's connection.

with db.execution_context():
    print(Names.table_exists())  # going to another context, this returns False if we are in :memory: and True if we work on a file *.db
    print id(db.get_conn())  # A separate connection.

print id(db.get_conn())  # Back to the original connection.

【问题讨论】:

  • 使用file::memory:?cache=shared 共享内存数据库。需要 sqlite 3.7.13 或更高版本(检查 sqlite3.sqlite_versionsqlite3.sqlite_version_info)。
  • 请注意,通常 Peewee 和 sqlite3 会让你跨线程共享连接;只需创建一个连接并在所有线程中使用它。见peewee.readthedocs.org/en/2.0.2/peewee/…
  • file::memory:?cache=shared 不幸的是不起作用:from peewee import * db = SqliteDatabase('file::memory:?cache=shared') db.connect() 给了我一个找不到文件的错误。我的 SQLite 版本是 3.11.0
  • 这可能是 Peewee 的限制;将重新打开。
  • 嗯,db = sqlite3.connect("file::memory:?cache=shared", uri=True) 抱怨 uri 不是有效的关键字,当我省略它时,会抛出“文件无法打开”异常。如果我想进行线程访问,似乎我不应该使用内存数据库。

标签: python sqlite peewee


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2011-10-04
    相关资源
    最近更新 更多