You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的sqlite3 Connection列出所有附加数据库?

如何列出Python sqlite3 Connection对象的所有附加数据库?

Python标准库的sqlite3模块没有直接提供类似list_databases()的内置方法,但可以通过执行SQLite原生的PRAGMA database_list指令实现,这和sqlite3命令行中的.databases命令功能完全一致。

实现示例

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("attach database 'a.db' as 'a'")
con.execute("attach database 'b.db' as 'b'")

# 查询所有附加数据库
cursor = con.execute("PRAGMA database_list")
databases = cursor.fetchall()

# 输出结果,每条记录格式为 (序号, 数据库别名, 文件路径)
for seq, db_name, db_file in databases:
    print(f"[{seq}] 数据库别名: {db_name}, 文件路径: {db_file}")

结果说明

返回的每条记录包含三个字段:

  • seq:数据库序号,主数据库(main)为0,临时数据库(temp)为1,附加数据库依次递增
  • db_name:数据库的别名(主库固定为main,临时库为temp,附加库是你attach时指定的名称)
  • db_file:数据库文件的路径,内存库(:memory:)为空字符串,磁盘数据库则是对应的文件路径

补充说明

sqlite_master是每个数据库自身的系统表,无法直接通过它获取当前连接的所有附加数据库列表,而PRAGMA database_list是SQLite专门提供的用于枚举当前连接所有数据库的指令,是最直接可靠的方式。

内容的提问来源于stack exchange,提问作者ACK_stoverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:27:12