You need to enable JavaScript to run this app. cursor.execute执行含更新SQL后转pandas DataFrame报错求解
优惠活动
大模型
产品
解决方案
定价
更多

cursor.execute执行含更新SQL后转pandas DataFrame报错求解

报错原因

pyodbc执行带OUTPUT的UPDATE语句后,cursor.fetchall()返回的是pyodbc自定义Row对象的列表,虽然打印输出时看起来和普通元组一致,但pandas默认会将每个Row实例识别为单个独立元素,因此传入DataFrame时被识别为只有1列的结构,和你指定的3个列名长度不匹配,触发形状不兼容报错。

解决方法

以下任意一种方案都可以解决问题:

  • 方案1:遍历rows将每个Row转为普通元组后再构造DataFrame
pending_files_df = pd.DataFrame([tuple(row) for row in rows], columns=names)
  • 方案2:使用pandas专门处理结构化记录的from_records方法构造
pending_files_df = pd.DataFrame.from_records(rows, columns=names)
补充优化建议

如果SQL语句没有匹配到符合条件的待更新行,cursor.fetchall()会返回空列表,此时cursor.description会为None,遍历取列名的代码会报错,建议增加非空判断逻辑:

if cursor.description:
    names = [x[0] for x in cursor.description]
    rows = cursor.fetchall()
    pending_files_df = pd.DataFrame([tuple(row) for row in rows], columns=names)
else:
    # 无匹配数据时构造空DataFrame
    pending_files_df = pd.DataFrame(columns=['Id', 'GCS_path', 'file_first_upload'])
cursor.commit()

内容的提问来源于stack exchange,提问作者Cristian Avendaño

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 11:45:05