`sqlite_master`:SQLite 的系统表,保存数据库结构信息

Caf5261 Caf5261 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

SQLite 中查看所有用户表的经典写法,逻辑是对的。我帮你简单说明一下,并补充一些常见注意点。

代码含义

cursor.execute("""
    SELECT name
    FROM sqlite_master
    WHERE type = 'table'
      AND name NOT LIKE 'sqlite_%'
""")
tables = [row[0] for row in cursor.fetchall()]
  • sqlite_master:SQLite 的系统表,保存数据库结构信息
  • type = 'table':只查询表(排除索引、视图等)
  • name NOT LIKE 'sqlite_%':排除 SQLite 内部系统表
  • 最终结果 tables 是一个用户表名列表

常见补充用法

1️⃣ 查看每张表的字段结构

for table in tables:
    cursor.execute(f"PRAGMA table_info({table})")
    columns = cursor.fetchall()
    print(table, columns)

2️⃣ 查看视图(如果你也需要)

cursor.execute("""
    SELECT name
    FROM sqlite_master
    WHERE type = 'view'
""")
views = [row[0] for row in cursor.fetchall()]

3️⃣ 同时查看表和视图

cursor.execute("""
    SELECT name, type
    FROM sqlite_master
    WHERE type IN ('table','view')
      AND name NOT LIKE 'sqlite_%'
""")

4️⃣ 如果你用的是 sqlite3 模块,推荐写法(防注入)

cursor.execute("""
    SELECT name
    FROM sqlite_master
    WHERE type = 'table'
      AND name NOT LIKE 'sqlite_%'
""")
tables = [row[0] for row in cursor]

小提醒

  • sqlite_master 不会显示临时表
  • 临时表在 sqlite_temp_master 中

如果你愿意,可以告诉我:

  • 用的是 Python + sqlite3 还是其他语言?
  • 是想检查表是否存在、自动建表,还是做数据库迁移/备份?

我可以按你的具体场景帮你优化这段代码。

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
Caf5261
Borter 10 成员 1,562 内容