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

Python使用pyodbc查询SQL Server时cursor.fetchall()判断失效求解

问题成因

pyodbc的游标对象在调用fetchall()方法后,会一次性读取当前查询结果集的全部数据,同时将游标指针移动到结果集的末尾,后续再次调用fetchall()时只会返回空列表。

你的代码中对同一个查询的结果连续调用了两次cursor.fetchall():

  • 输入存在的有效SKU时,第一次if判断调用cursor.fetchall()会返回非空列表,==[]的条件不成立,进入elif判断逻辑
  • 此时第二次调用cursor.fetchall()已经无数据可读取,返回结果为空列表,!=[]的条件同样不成立,因此无任何输出
  • 输入不存在的无效SKU时,第一次调用cursor.fetchall()就返回空列表,直接触发if分支输出,因此仅有效SKU场景会出现异常。
修复方案

仅调用一次cursor.fetchall(),将返回结果存入本地变量后再做分支判断即可,修正后代码如下:

import pyodbc as odbc

Driver = 'SQL Server'
server_name = ''
database_name = ''

conn = odbc.connect(f"""
    Driver={{{Driver}}};
    Server={server_name};
    Database={database_name};
    UID=;
    PWD=;
                      """)


def sku_search():
    SKU_check = '''SELECT [ITEMSKU] FROM
    [StilettoXT].[dbo].[PRODDETAIL] WHERE
    ITEMSKU = (?)'''
    SKU_code = input('Please enter the SKU code: ')
    cursor = conn.cursor()
    cursor.execute(SKU_check, SKU_code)
    # 仅调用一次fetchall,将结果存到变量
    res = cursor.fetchall()
    if res == []:
        print('Not Found')
    else:
        print('Found')

sku_search()
conn.close()

优化建议

如果仅需要判断SKU是否存在,不需要读取全部匹配结果,可使用cursor.fetchone()替代cursor.fetchall(),减少不必要的资源消耗:

res = cursor.fetchone()
if res is None:
    print('Not Found')
else:
    print('Found')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 01:51:04