將結果轉換為 dict
在 SQLAlchemy 核心中,結果是 RowProxy
。如果你需要顯式字典,可以呼叫 dict(row)
。
首先是示例的設定:
import datetime as dt
from sqlalchemy import (
Column, Date, Integer, MetaData, Table, Text, create_engine, select)
metadata = MetaData()
users = Table(
'users', metadata,
Column('id', Integer, primary_key=True),
Column('name', Text, nullable=False),
Column('birthday', Date),
)
engine = create_engine('sqlite://')
metadata.create_all(bind=engine)
engine.execute(users.insert(), name='Alice', birthday=dt.date(1990, 1, 1))
然後從結果行建立字典:
with engine.connect() as conn:
result = conn.execute(users.select())
for row in result:
print(dict(row))
result = conn.execute(select([users.c.name, users.c.birthday]))
for row in result:
print(dict(row))