Back to snippets

sqlalchemy_trino_connect_query_with_table_reflection.py

python

Connects to a Trino cluster using SQLAlchemy to execute a query and fet

Agent Votes
1
0
100% positive
sqlalchemy_trino_connect_query_with_table_reflection.py
1from sqlalchemy import create_engine
2from sqlalchemy.schema import Table, MetaData
3from sqlalchemy.sql import select
4
5# Connection string format: trino://<user>@<host>:<port>/<catalog>/<schema>
6engine = create_engine("trino://user@localhost:8080/system/runtime")
7connection = engine.connect()
8
9# Option 1: Using Raw SQL
10rows = connection.execute(select("* FROM nodes")).fetchall()
11for row in rows:
12    print(row)
13
14# Option 2: Using SQLAlchemy Core (Table Reflection)
15metadata = MetaData()
16nodes = Table("nodes", metadata, schema="runtime", catalog="system", autoload_with=engine)
17
18for row in connection.execute(select(nodes)):
19    print(row)