Schema einer SQLite3-Tabelle in Python abrufen

English Deutsch

Siehe auch Tabellenschema für SQLite3-Tabelle auf der Kommandozeile anzeigen

Verwende diese Funktion, um das Tabellenschema einer SQLite3-Tabelle in Python zu finden:

sqlite_table_schema.py
def sqlite_table_schema(conn, name):
    """Gibt einen String zurück, der das CREATE der Tabelle repräsentiert"""
    cursor = conn.execute("SELECT sql FROM sqlite_master WHERE name=?;", [name])
    sql = cursor.fetchone()[0]
    cursor.close()
    return sql

Verwendungsbeispiel:

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

Vollständiges Beispiel:

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'))

welches Folgendes ausgibt

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