如何在 Python 中列出 SQLite3 数据库中的表

另请参见如何在命令行上列出 SQLite3 数据库表

你可以使用此代码片段在 Python 中列出 SQLite 3.x 数据库中的所有 SQL 表:

list_tables.py
def tables_in_sqlite_db(conn):
    cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = [
        v[0] for v in cursor.fetchall()
        if v[0] != "sqlite_sequence"
    ]
    cursor.close()
    return tables

用法示例:

usage_example.py
#!/usr/bin/env python3
import sqlite3
# 打开数据库
conn = sqlite3.connect('/usr/share/command-not-found/commands.db')
# 列出表
tables = tables_in_sqlite_db(conn)

# 你的代码放在这里!
# 示例:
print(tables) # 打印 ['commands', 'packages']

Check out similar posts by category: Databases, Python, SQLite