Thursday, May 4, 2023

Python Sqlite3 Functions

def gettablenames(db) -> list[str]:
    with sqlite3.connect(db) as conn:
        cursor: sqlite3.Cursor = conn.cursor()
        # querygtnS = 'SELECT name FROM sqlite_schema WHERE type = "table"'
        querygtnS = 'SELECT name FROM sqlite_master WHERE type = "table" AND name NOT LIKE "sqlite_%" ORDER BY name'
        cursor.execute(querygtnS)
        tablenames = cursor.fetchall()
        tablenames: list[str] =[tablename[0] for tablename in tablenames]
        print(*tablenames, sep=' - ')
    return tablenames
def gettablenamesPRAGMA(db) -> list[str]:
    with sqlite3.connect(db) as conn:
        cursor: sqlite3.Cursor = conn.cursor()
        querygtnP = 'PRAGMA table_list'
        cursor.execute(querygtnP)
        tablenames = cursor.fetchall()
        tablenames: list[str] =[tablename[1] for tablename in tablenames if 'sqlite_' not in tablename[1]]
    return tablenames

if __name__ == '__main__':
    db = 'db.db'
    tablenames: list[str] = gettablenames(db)
    print(*tablenames, sep=' - ')