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

Wil*_*hin 8 python sqlite

我想合并SQLite数据库,有些可能在内存中.我通过将数据库路径指定为来创建内存数据库:memory:.在这篇文章之后,使用attachSQLite 的功能似乎是一种简单而有效的方法.但是如何指定我的内存数据库作为附加源?

例如,我想做类似的事情:

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(), ))
Run Code Online (Sandbox Code Playgroud)

但是,当然,这c1.get_attach_id()是我为演示目的而制作的一种方法,因为使用字符串:memory:会很模糊.如何指定现有c1数据库?

Mar*_*ers 19

:memory:连接到内存数据库的纯字符串无法与其他连接共享或连接.

您需要使用带有参数的file: URI文件名连接字符串?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")
Run Code Online (Sandbox Code Playgroud)

请参阅内存数据库文档.

请注意,只能有一个这样的共享内存数据库; 所有其他内存数据库必须保持其连接的私有状态.如果需要更复杂的设置,请将数据库与实际文件系统存储一起使用; 如果你在每个tempfile.mkdtemp()临时目录中创建这些,这些都很容易随后清理.

演示:

>>> 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')]
Run Code Online (Sandbox Code Playgroud)

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

>>> sqlite3.sqlite_version_info
(3, 8, 10, 2)
Run Code Online (Sandbox Code Playgroud)