SQLAlchemy - Getting a list of tables

前端 未结 9 1051
青春惊慌失措
青春惊慌失措 2020-12-08 03:40

I couldn\'t find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy?

I used the class method to create the tab

相关标签:
9条回答
  • 2020-12-08 04:02

    The metadata object that you created the tables with has that in a dictionary.

    metadata.tables.keys()
    
    0 讨论(0)
  • 2020-12-08 04:03

    Just this simple:

    engine.table_names()
    

    Also, to test whether a table exists:

    engine.has_table(table_name)
    
    0 讨论(0)
  • 2020-12-08 04:05
    from sqlalchemy import create_engine
    engine = create_engine('postgresql://use:pass@localhost/DBname')
    print (engine.table_names())
    
    0 讨论(0)
  • 2020-12-08 04:11

    I was looking for something like this:

    from sqlalchemy import create_engine
    eng = create_engine('mysql+pymysql://root:password@localhost:3306', pool_recycle=3600)
    q = eng.execute('SHOW TABLES')
    
    available_tables = q.fetchall()
    

    It does an execute and returns all of the tables.

    update:

    Postgres:

    eng = create_engine('postgresql+psycopg2://root:password@localhost/
    q = eng.execute('SELECT * FROM pg_catalog.pg_tables')
    
    0 讨论(0)
  • 2020-12-08 04:12

    I'm solving same problem and found this post. After some try run, I would suggest use below to list all tables: (mentioned by zerocog)

    metadata = MetaData()
    metadata.reflect(bind=engine)
    for table in metadata.sorted_tables:
        print(table)
    

    This is useful for direct table handling and I feel is recommended.

    And use below code to get table names:

    for table_name in engine.table_names():
        print(table_name)
    

    "metadata.tables" provides a Dict for table name and Table object. which would also be useful for quick query.

    0 讨论(0)
  • 2020-12-08 04:14

    Within the python interpreter use db.engine.table_names()

    $ python
    >>> from myapp import db
    >>> db.engine.table_names()
    
    0 讨论(0)
提交回复
热议问题