[英]Python sqlite3: how to check if connection is an in-memory database?
From Python's sqlite3 library, how can we determine if a connection belongs to a in-memory database?从 Python 的 sqlite3 库中,我们如何确定一个连接是否属于内存数据库?
import sqlite3
conn = sqlite3.connect(':memory:')
def is_in_memory_connection(conn):
# How to check if `conn` is an in-memory connection?
Is it possible to check the filename of an on-disk database?是否可以检查磁盘数据库的文件名? If so, I would presume that it would return
None
for an in-memory database.如果是这样,我会假设它会为内存数据库返回
None
。
This is the closest I could come up with:这是我能想到的最接近的:
import sqlite3
def is_in_memory_connection(conn):
local_cursor = conn.cursor()
local_cursor.execute('pragma database_list')
rows = local_cursor.fetchall()
print(rows[0][2])
return rows[0][2] == ''
#database = 'test.sqlite'
database = ':memory:'
conn = sqlite3.connect(database)
result = is_in_memory_connection(conn)
print(result)
If you have an in-memory database, database_list will show equivalent of this:如果您有一个内存数据库,database_list 将显示与此等效的内容:
sqlite> pragma database_list;
seq name file
--- ---- ----
0 main
If you are opening a file that's on disk, it'll show the path of the file equivalent of this:如果您打开磁盘上的文件,它将显示与此等效的文件路径:
sqlite> pragma database_list;
seq name file
--- ---- --------------------------
0 main /home/testing/test.sqlite
Taking advantage of this, you could call pragma database_list
to show the file.利用这一点,您可以调用
pragma database_list
来显示文件。 If the path is empty, the database is not associated with a file.如果路径为空,则数据库未与文件相关联。
https://sqlite.org/pragma.html#pragma_database_list https://sqlite.org/pragma.html#pragma_database_list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.