List database tables with SQLAlchemy

前端 未结 4 1282
心在旅途
心在旅途 2020-12-13 01:52

I want to implement a function that gives information about all the tables (and their column names) that are present in a database (not only those created with SQLAlchemy).

4条回答
  •  盖世英雄少女心
    2020-12-13 02:37

    start with an engine:

    from sqlalchemy import create_engine
    engine = create_engine("postgresql://u:p@host/database")
    

    quick path to all table /column names, use an inspector:

    from sqlalchemy import inspect
    inspector = inspect(engine)
    
    for table_name in inspector.get_table_names():
       for column in inspector.get_columns(table_name):
           print("Column: %s" % column['name'])
    

    docs: http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html?highlight=inspector#fine-grained-reflection-with-inspector

    alternatively, use MetaData / Tables:

    from sqlalchemy import MetaData
    m = MetaData()
    m.reflect(engine)
    for table in m.tables.values():
        print(table.name)
        for column in table.c:
            print(column.name)
    

    docs: http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html#reflecting-all-tables-at-once

提交回复
热议问题