You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLAlchemy中获取connection.execute查询结果的列类型

获取SQLAlchemy查询结果集的列数据类型

当你通过connection.execute()执行查询得到Result对象后,有两种常用方式获取结果集列的数据类型:

方式一:利用SQLAlchemy封装的Result.columns属性

这是最推荐的方式,SQLAlchemy会直接返回封装好的列类型对象,可读性强。

示例代码:

from sqlalchemy import create_engine

# 初始化引擎并建立连接
engine = create_engine("your_database_url_here")
with engine.connect() as conn:
    # 执行查询
    result = conn.execute("SELECT id, username, register_time FROM users")
    
    # 遍历列对象,映射列名到对应的数据类型
    column_type_map = {col.name: col.type for col in result.columns}
    
    # 输出结果
    for col_name, col_type in column_type_map.items():
        print(f"列 {col_name} 的数据类型: {col_type}")

输出示例(以SQLite为例):

列 id 的数据类型: INTEGER()
列 username 的数据类型: VARCHAR(length=64)
列 register_time 的数据类型: DATETIME()
  • 对于带别名的查询(比如SELECT user_id AS id FROM users),col.name会返回你指定的别名id,类型对应原列的实际类型
  • col.type返回的是SQLAlchemy定义的类型对象,比如Integer、String、DateTime等,和你定义表结构时用的类型一致

方式二:通过数据库游标描述获取原生类型信息

如果你需要数据库底层的原生类型编码,可以直接访问result.cursor.description,这是DBAPI游标提供的原生信息:

示例代码:

with engine.connect() as conn:
    result = conn.execute("SELECT id, username FROM users")
    # 游标描述的每个元素包含列的元数据,索引1对应原生类型编码
    for col_desc in result.cursor.description:
        col_name = col_desc[0]
        native_type_code = col_desc[1]
        print(f"列 {col_name} 的原生类型编码: {native_type_code}")

这种方式返回的是数据库驱动定义的类型编码(比如SQLite中INTEGER的编码是1),适合需要和底层数据库交互的场景,但可读性不如第一种方式。

内容的提问来源于stack exchange,提问作者Test

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:02:07