sqlsqlalchemy

displaying all tables with different schema with SQLalchemy's MetaData


I have some trouble displaying all table names from my database. Is there an option where I can skip the specification of the exact table schema?

    def display(self):
       m = MetaData()
       m.reflect(self.engine,schema = "schemaname")
       for table in m.tables.values():
           print(table.name)

This works fine for all the tables with the specific schema name but couldn't find any information for how to display all of them. When I don't mention the schema name in .reflect() no table names are shown.


Solution

  • m.reflect can get only one schema. if schema option is None, get public schema tables. if you want to get all schema table you need to schema list first.

    from sqlalchemy import create_engine, inspect, MetaData
    
    engine = create_engine('CONNECTION_STRING')
    
    inspector = inspect(engine)
    
    for schema in inspector.get_schema_names():
        for table in inspector.get_table_names(schema):
            print(table.name)
    

    this schema list has infomation_shcema. if no need, you need to except this shcema infomation.