'SQLAlchemy: Selecting with Textual Column Expressions use-cases

Can someone provide me with some use-cases for the "Selecting with Textual Column Expressions" concept of SQLAlchemy?

I fail to see the point behind the given examples in the documentation.

Thank you in advance.



Solution 1:[1]

One example would be if we wanted to run the query

SELECT protocol_version FROM sys.dm_exec_connections

against a SQL Server database. sys.dm_exec_connections is a system view, not a real table, so this fails:

tbl = sa.Table(
    "dm_exec_connections", sa.MetaData(), schema="sys", autoload_with=engine
)
# sqlalchemy.exc.NoSuchTableError: dm_exec_connections

However, this works:

stmt = sa.text("SELECT protocol_version FROM sys.dm_exec_connections")

with engine.connect() as conn:
    result = conn.execute(stmt).first()
    print(result.protocol_version)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gord Thompson