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

2024-06-26 13:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想合并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数据库?


Tags: 方法内存id数据库executesqlitegetconnect
1条回答
网友
1楼 · 发布于 2024-06-26 13:33:38

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

需要使用带file: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

注意,只有一个这样的共享内存数据库;所有其他内存数据库必须对其连接保持私有。如果您需要更复杂的设置,请使用具有实际文件系统存储的数据库;如果您在每个数据库中创建这些设置,这些设置很容易在以后进行清理。

演示:

>>> 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)

相关问题 更多 >