SQLite inmemory数据库没有被销毁?

2024-05-16 20:10:05 发布

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

我编写了这个非常简单的测试脚本来检查内存中共享缓存数据库的功能,并且似乎在脚本退出后数据库没有被清理。在

import sqlite3

def hello():
    db = sqlite3.connect('file::memory:?cache=shared')
    db.execute("CREATE TABLE test (hello varchar(32))")
    db.execute("INSERT INTO test (hello) VALUES ('world')")
    db.commit()
    c1 = db.execute("SELECT * FROM test")
    print c1.fetchone()
    db.close()

def world():
    wdb = sqlite3.connect('file::memory:?cache=shared')
    c = wdb.execute("SELECT * FROM test")
    print c.fetchone()
    wdb.close()


hello()
world()

我第一次运行这个脚本时,它没有出现问题,但我忘记了最后的决定。第二次运行它时,我得到一个异常,说表已经存在。我知道,很明显,我可以将IF NOT EXISTS添加到CREATE TABLE语句中,但这种行为似乎意味着数据库仍在内存中。我正确地解释了吗?如果是这样,有没有办法把它清理干净?在

我尝试过对查询进行注释,并简单地打开/关闭连接,但似乎没有任何效果。在


Tags: 内存test脚本数据库cachehelloworldexecute
1条回答
网友
1楼 · 发布于 2024-05-16 20:10:05

python2.7中的pythonsqlite3模块不支持URI文件名。db = sqlite3.connect('file::memory:?cache=shared')实际上在磁盘上创建了一个名为“file::memory:?cache=shared“,你每次都连接到它。在

相反,只需执行db = sqlite3.connect(':memory:'),尽管不会获得共享缓存行为。在

这种行为has been fixed,但仅在Python3.4中,并且需要传递uri=Truekwarg。在

相关问题 更多 >