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
相关产品推荐
相关产品推荐

