当前位置:首页 > 数据库 > SQlite

如何在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作为对新创建的数据库的引用.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!