List database tables with SQLAlchemy

前端 未结 4 1274
心在旅途
心在旅途 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:23

    First set up the sqlalchemy engine.

    from sqlalchemy import create_engine, inspect, text
    from sqlalchemy.engine import url
    
    connect_url = url.URL(
        'oracle',
        username='db_username',
        password='db_password',
        host='db_host',
        port='db_port',
        query=dict(service_name='db_service_name'))
    
    engine = create_engine(connect_url)
    
    try:
        engine.connect()
    except Exception as error:
        print(error)
        return
    

    Like others have mentioned, you can use the inspect method to get the table names.

    But in my case, the list of tables returned by the inspect method was incomplete.

    So, I found out another way to find table names by using pure SQL queries in sqlalchemy.

    query = text("SELECT table_name FROM all_tables where owner = '%s'"%str('db_username'))
    
    table_name_data = self.session.execute(query).fetchall()
    

    Just for sake of completeness of answer, here's the code to fetch table names by inspect method (if it works good in your case).

    inspector = inspect(engine)
    table_names = inspector.get_table_names()
    

提交回复
热议问题