SQLAlchemy 获取查询结果的列数据类型
from sqlalchemy import create_engine, MetaData, ForeignKey
engine = create_engine("mysql://user:passwd@localhost/shema", echo=False)
meta = MetaData(engine, True)
conn = engine.connect()
tb_list = meta.tables["tb_list"]
tb_data = meta.tables["tb_data"]
tb_list.c.i_data.append_foreign_key( ForeignKey(tb_data.c.i_id) )
q = tb_list.outerjoin(tb_data).select()
res = conn.execute(q)
那么,我该如何获取查询结果 res
的列类型呢?
这是其中一个解决方案:
res._key_cache[ col_name ][0]
你还有其他的想法吗?
1 个回答
19
你可以这样说:
types = [col.type for col in q.columns]
如果你想深入了解,编译后的语句也在结果里:
types = [col.type for col in res.context.compiled.statement.columns]
如果你想要数据库API版本的类型,这个会根据数据库API的不同而有所变化:
types = [elem[1] for elem in res.cursor.description]
也许我们会考虑将这种元数据更直接地添加到 ResultProxy
中。