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

使用pyodbc搭配pandas查询SQL时返回DataFrame缺失1行问题求助

问题根因

你的数据缺失和pd.set_option配置没有任何关系,问题出在SQL_Query函数里的游标读取逻辑:

  • pyodbc的游标查询结果是单向读取的,缓冲区数据被读取后就不会再次返回
  • 你执行cursor.execute(query_string)后,先调用了一次row = cursor.fetchone(),把第一条结果行提前读走了,且后续没有用到这个row变量
  • 后续调用cursor.fetchall()时只能读取到剩下的1条结果,所以最终DataFrame只有1行数据

修复方法

直接删除冗余的row = cursor.fetchone()这行代码即可,修改后的游标读取逻辑如下:

cursor.execute(query_string)
# 删掉多余的fetchone行
desc = cursor.description
column_names = [col[0] for col in desc]
data = [dict(zip(column_names, row)) for row in cursor.fetchall()]

优化建议

你可以直接用pandas内置的read_sql_query方法直接从数据库连接读取数据,无需手动处理游标、列名和数据组装,代码更简洁也不容易出问题:

def SQL_Query(query_string):
    import pyodbc as p
    import pandas as pd

    pd.set_option("display.max_rows", None)
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", 1000)

    databaseName = '***'
    username = '***'
    password = '***'
    server = '***'
    driver = '***'

    CONNECTION_STRING = f'DRIVER={driver};SERVER={server};DATABASE={databaseName};UID={username};PWD={password}'
    conn = p.connect(CONNECTION_STRING)
    # 直接读取为DataFrame
    df = pd.read_sql_query(query_string, conn)
    conn.close()

    if not df.empty:
        qty_total = str(df['InitialQuantity'].sum())
        qty_RT = str(df['RT'].sum())
        print('Number of units found with criteria: ' + qty_total)
        print('Number of units with RT:             ' + qty_RT + '\n')
        print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:24:04