删除 :memory 中的数据库文件:

sun*_*ata 4 python sqlite python-3.x python-unittest

背景和问题

我们在:memory:测试时使用来存储我们的数据库,并希望在每个测试用例运行之前将其删除,以便我们从每个测试用例的空数据库开始。(如果我们将数据库存储在磁盘上,我们只需删除文件)

我们的设置

  • 我们正在使用 Python 的unittest模块
  • (Python 版本:3.6)
  • 这是我们创建数据库的样子: db_connection = sqlite3.connect(":memory:")

我们如何从内存中删除我们的数据库?

13s*_*ver 6

使用连接方法close()。它将关闭您与数据库的连接。如果数据库在内存中,您应该无法重新连接到它。

您可以简单地对此进行测试:

import sqlite3
conn = sqlite3.connect(':memory:')

c = conn.cursor()
c.execute('CREATE TABLE test (col1 text, col2 text)')
c.execute("INSERT INTO test VALUES ('good', 'day')")
conn.commit()
conn.close()
Run Code Online (Sandbox Code Playgroud)

然后我们可以检查我们是否可以访问数据库。

conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("SELECT * FROM test")
print(c.fetchall())
Run Code Online (Sandbox Code Playgroud)

c.execute("SELECT * FROM test")

sqlite3.OperationalError:没有这样的表:测试

这向我们表明,当您在内存中关闭数据库时,它会被销毁。