python-3.xsql-serversqlalchemyorm

How to get a Table Object by table's name by sqlalchemy and query in it?


I want to query some information from a pointed table in a database(I don't like native SQL sentences), and this is my code:

import sqlalchemy as sqa

sl_database_link = 'mssql+pymsql://……'
sl_engine = sqa.create_engine(sl_database_link)
session = scoped_session(sessionmaker(bind=sl_engine))
insp_sl = inspect(sl_engine)
tables = insp_sl.get_table_names()
session.query('the table which I want to query')

But after I getting a table name, I don't know how to query the table by its name correctly, can someone tell me?

I have find some posts on StackOverflow, but every result can't solve my problem.


Solution

  • If you want to query a single table you get the object via the Table class.

    import sqlalchemy as sa
    ...
    tbl = sa.Table(name_of_table, sa.MetaData(), autoload_with=engine)
    
    with engine.connect() as conn:
        rows = conn.execute(sa.select(tbl))
    

    If you want more than one table you can use metadata.reflect:

    metadata = sa.MetaData()
    # Omit "only" to reflect all tables
    metadata.reflect(engine, only=[name_of_table1, name_of_table2, ...])
    my_table = metadata.tables[name_of_table]
    

    See the docs for Reflecting Database Objects and, if you prefer to work with ORM models, the Automap extension.