微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Python中将内存中的SQLite数据库复制到另一个内存中的SQLite数据库?

我正在为Django编写一个测试套件,它以树状方式运行测试.例如,Testcase A可能有2个结果,Testcase B可能有1个,Testcase C可能有3个.树看起来像这样

      X
     /
A-B-C-X
 \   \
  B   X
   \   X
    \ /
     C-X
      \
       X

对于上面树中的每个路径,数据库内容可能不同.所以在每个fork中,我正在考虑创建数据库当前状态的内存副本,然后将该参数提供给下一个测试.

任何人都知道如何将内存数据库实质上复制到另一个数据库,然后获得传递该数据库的引用?

谢谢!

解决方法:

好吧,经过一次有趣的冒险之后,我想出了这个.

from django.db import connections
import sqlite3

# Create a Django database connection for our test database
connections.databases['test'] = {'NAME': ":memory:", 'ENGINE': "django.db.backends.sqlite3"}

# We assume that the database under the source_wrapper hasn't been created
source_wrapper = connections['default']  # put alias of source db here
target_wrapper = connections['test'] 

# Create the tables for the source database
source_wrapper.creation.create_test_db()

# Dump the database into a single text query
query = "".join(line for line in source_wrapper.connection.iterdump())

# Generate an in-memory sqlite connection
target_wrapper.connection = sqlite3.connect(":memory:")
target_wrapper.connection.executescript(query)

现在,名为test的数据库将成为数据库的副本.使用target_wrapper.connection作为对新创建的数据库的引用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐