【问题标题】:"TypeError: 'NoneType' object is not iterable" from pandas read_sql来自 pandas read_sql 的“TypeError:'NoneType' 对象不可迭代”
【发布时间】:2020-01-11 23:33:43
【问题描述】:

我正在尝试在 python 中使用 pyodbc 运行 SQL 命令。 其中 SQL 命令包含多个 SELECT 命令和 IF 语句。

但我收到如下错误

columns = [col_desc[0] for col_desc in cursor.description]
TypeError: 'NoneType' object is not iterable

import pyodbc
import pandas as pd
conn = pyodbc.connect("DRIVER={SQL Server};"
                "SERVER=server_name;"
                "DATABASE=master;"
                "Trusted_Connection=yes;")
cursor = conn.cursor()
script="""

If object_id ('tempdb..#Temp1')is not null
drop table #Temp1
Select distinct  a1.some_ID into #Temp1
from DOC.dbo.Document_tbl (NOLOCK)a1
from #Temp1 a1
If object_id ('tempdb..#Temp2')is not null
Drop table #Temp2
select distinct v2.some_data
into #Temp2 from tbl_name (nolock) v2 

If object_id ('tempdb..#Results')is not null
drop table #Results
select distinct a1.*,b1.####
into #Results
from #Temp1 a1
left join #Temp2 b1 on a1.## = b1.##
Select * from #Results
"""

df = pd.read_sql(script, cnxn)
writer = pd.ExcelWriter('result.xlsx')
df.to_excel(writer, sheet_name ='bar')
writer.save()

【问题讨论】:

  • 报错说光标里面什么都没有,基本上就是你什么都没有返回。
  • 请删除那些NOLOCK 查询提示,除非您完全了解为什么需要它们以及使用它们的风险,包括检索无效数据和不存在的数据
  • 谢谢戈德·汤普森

标签: python sql-server pandas pyodbc


【解决方案1】:

包含多个 SQL 语句的 SQL 命令文本称为匿名代码块。一个匿名代码块可以返回多个结果,其中每个结果可以是

  • 行数,
  • 包含零行或多行数据的结果集,或
  • 一个错误。

下面的例子失败了……

sql = """\
SELECT 1 AS foo INTO #tmp;
SELECT * FROM #tmp;
"""
df = pd.read_sql_query(sql, cnxn)
# TypeError: 'NoneType' object is not iterable

...因为第一个 SELECT ... INTO 在第二个 SELECT 返回其结果集之前返回行数。

修复方法是使用SET NOCOUNT ON; 启动匿名代码块,这会抑制行数并仅返回结果集:

sql = """\
SET NOCOUNT ON;
SELECT 1 AS foo INTO #tmp;
SELECT * FROM #tmp;
"""
df = pd.read_sql_query(sql, cnxn)
# no error

【讨论】:

    【解决方案2】:

    对于仍然遇到此错误的其他人,我发现对于某些语句(聚合空值的窗口函数)我还需要包含 SET ANSI_WARNINGS OFF;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 2015-11-04
      • 2020-03-18
      • 2012-08-25
      • 1970-01-01
      相关资源
      最近更新 更多