如何在 Python 中获取 SQLite3 表的架构

另请参见如何在命令行上显示 SQLite3 表的表架构

使用此函数在 Python 中查找 SQLite3 表的表架构:

sqlite_table_schema.py
def sqlite_table_schema(conn, name):
    """返回表示表的 CREATE 语句的字符串"""
    cursor = conn.execute("SELECT sql FROM sqlite_master WHERE name=?;", [name])
    sql = cursor.fetchone()[0]
    cursor.close()
    return sql

用法示例:

sqlite_table_schema_usage.py
print(sqlite_table_schema(conn, 'commands'))

完整示例:

sqlite_table_schema_full.py
#!/usr/bin/env python3
import sqlite3
conn = sqlite3.connect('/usr/share/command-not-found/commands.db')

def sqlite_table_schema(conn, name):
    cursor = conn.execute("SELECT sql FROM sqlite_master WHERE name=?;", [name])
    sql = cursor.fetchone()[0]
    cursor.close()
    return sql

print(sqlite_table_schema(conn, 'commands'))

打印

commands_schema.sql
CREATE TABLE "commands"
           (
            [cmdID] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
            [pkgID] INTEGER NOT NULL,
            [command] TEXT,
            FOREIGN KEY ([pkgID]) REFERENCES "pkgs" ([pkgID])
           )

Check out similar posts by category: Python, SQLite