python - 如何在 Python 中附加内存中的 SQLite 数据库?

标签 python sqlite

我想合并 SQLite 数据库,有些可能在内存中。我通过将数据库路径指定为 :memory: 来创建内存数据库。正在关注this post ,使用 SQLite 的 attach 功能似乎是一种简单而有效的方法。但是,如何将我的内存数据库指定为要附加的源?

例如,我想做这样的事情:

c1 = sqlite3.connect(":memory:")
c1.execute(...create table, insert a bunch, commit...)

c2 = sqlite3.connect(":memory:")
c2.execute("""
  ATTACH ? AS ToMerge;
  BEGIN; 
    INSERT INTO Records SELECT * FROM ToMerge.Records; 
  COMMIT;
""", (c1.get_attach_id(), ))

但是,当然,c1.get_attach_id() 是我为演示目的而编写的方法,因为使用字符串 :memory: 会产生歧义。如何指定现有的 c1 数据库?

最佳答案

连接到内存数据库的普通 :memory: 字符串不能从其他连接共享或附加。

您需要使用一个文件: URI filename connection string使用 ?cache=shared 参数可以在连接之间共享内存数据库;然后你也可以附加到它:

# first connection
c1 = sqlite3.connect("file::memory:?cache=shared", uri=True)

# second connection, to the *same database*
c2 = sqlite3.connect("file::memory:?cache=shared", uri=True)

# third connection, to a different database altogether
c3 = sqlite3.connect('/tmp/sqlite3.db', uri=True)
# can attach to the shared in-memory database, but only if you used
# uri=True on the original connection
c3.execute("ATTACH DATABASE 'file::memory:?cache=shared' AS inmem")

参见 In-Memory Databases documentation .

请注意,只能有一个这样的共享内存数据库;所有其他内存数据库必须对其连接保持私有(private)。如果您需要更复杂的设置,请使用具有实际文件系统存储的数据库;如果您在 tempfile.mkdtemp() temporary directory 中创建它们,那么这些很容易在事后清理每一个。

演示:

>>> import sqlite3
>>> c1 = sqlite3.connect("file::memory:?cache=shared", uri=True)
>>> c1.execute('CREATE TABLE foo (bar, baz)')
<sqlite3.Cursor object at 0x106839490>
>>> c1.execute("INSERT INTO foo VALUES ('spam', 'ham')")
<sqlite3.Cursor object at 0x106839500>
>>> c1.commit()
>>> c2 = sqlite3.connect("file::memory:?cache=shared", uri=True)
>>> list(c2.execute('SELECT * FROM foo'))
[(u'spam', u'ham')]
>>> c3 = sqlite3.connect('/tmp/sqlite3.db', uri=True)
>>> c3.execute("ATTACH DATABASE 'file::memory:?cache=shared' AS inmem")
<sqlite3.Cursor object at 0x1068395e0>
>>> list(c3.execute('SELECT * FROM inmem.foo'))
[(u'spam', u'ham')]

对内存共享缓存连接的支持已添加到 SQLite 3.7.13 版;对于 Python,您可以使用 sqlite3.sqlite_version(字符串)或 sqlite3.sqlite_version_info(带整数的元组)检查底层库的版本:

>>> sqlite3.sqlite_version_info
(3, 8, 10, 2)

关于python - 如何在 Python 中附加内存中的 SQLite 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32681761/

相关文章:

android - 如何使 Sqlite 中的字段唯一?

android - 将数据从表复制到表sqlite android

ruby - 如何使用 sqlite/sequel 选择星期一?

Python 数组,试图将文本文件放入数组中

python stdout flush 和 tee

python - Cartesi Rollups 中的门户是如何工作的?

python - Rdd lambda 函数围绕行与列的混淆

python - 如何更改 pyplot 上的 yticks?

java - 如何从一次只返回一行的函数中获取 SQLite 的每一行

ios - 如何将已填充的 SQLite 数据库与 SharkORM 结合使用