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

SQL查询结果与Excel数据对比异常:打印一致但判断不匹配

Excel数据与SQL查询结果匹配异常问题

尝试对比Excel导出的数据与SQL查询结果,打印显示两者内容、外层类型均一致,但用for循环+if判断时,却提示所有数据不匹配。

运行代码

import pandas as pd
import pyodbc

xlsx = pd.read_excel(r'SrcExcelFile.xlsx')
out = xlsx.to_numpy().tolist()
out1 = [tuple(elt) for elt in out]

conn_str = (r'connection')
cnxn = pyodbc.connect(conn_str)
with open(r'Target_1.sql') as Q1:
    ReadTargetFile2 = Q1.read()
cursor = cnxn.cursor()
SQL_QUERY = cursor.execute(ReadTargetFile2)
sqlResult = cursor.fetchall()

print(out1)
print(sqlResult)

print(type(out1))
print(type(sqlResult))

for rctest in sqlResult :
    if rctest in out1:
        print('%s is in SRC' % rctest[0])
    else:
        print('%s is not in SRC' % rctest[0])
exit()

运行结果

[('Test1', 'Y'), ('Test2', 'Y'), ('Test3', 'Y')]
[('Test1', 'Y'), ('Test2', 'Y'), ('Test3', 'Y')]

<class 'list'>
<class 'list'>

Test1 is not in SRC
Test2 is not in SRC
Test3 is not in SRC

问题原因

pyodbc的fetchall()返回的是pyodbc.Row对象组成的列表,虽然打印时外观和元组一致,但实际类型不是Python原生元组。而out1里的元素是标准tuple,两者类型不匹配,导致in判断无法识别为相同元素。

解决办法

把sqlResult中的每个Row对象转换为原生元组,修改代码如下:

# 替换原sqlResult的赋值行
sqlResult = [tuple(row) for row in cursor.fetchall()]

修改后重新执行判断,即可正常匹配数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:54:54