pandas 熊猫中的 NoneType 对象不是可迭代的错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30534095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:24:58  来源:igfitidea点击:

NoneType object is not iterable error in pandas

pythonsql-serverpandas

提问by Himanshu Gupta

I am trying to pull some data from a stored proc on a sql server using python.

我正在尝试使用 python 从 sql 服务器上的存储过程中提取一些数据。

Here is my code:

这是我的代码:

import datetime as dt
import pyodbc
import pandas as pd

conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server Native client 11.0}',server = '*****, database = '**')

pd.read_sql("EXEC ******** '20140528'",conn)

I get the error: TypeError: 'NoneType' object is not iterable

我收到错误:TypeError: 'NoneType' object is not iterable

I suspect this is because I have a cell in the sql table with value NULL but not sure if that's the true reason why I am getting the error. I have run many sql statements using the same code without any errors.

我怀疑这是因为我在 sql 表中有一个值为 NULL 的单元格,但不确定这是否是我收到错误的真正原因。我已经使用相同的代码运行了许多 sql 语句,没有任何错误。

Here's the traceback:

这是回溯:

In[39]: pd.read_sql("EXEC [dbo].[] '20140528'",conn)
Traceback (most recent call last):
  File "C:*", line 3032, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-39-68fb1c956dd7>", line 1, in <module>
    pd.read_sql("EXEC [dbo].[] '20140528'",conn)
  File "C:*", line 467, in read_sql
    chunksize=chunksize
  File "c:***", line 1404, in read_query
    columns = [col_desc[0] for col_desc in cursor.description]
TypeError: 'NoneType' object is not iterable

回答by Korone

Your sproc needs

您的 sproc 需求

SET NOCOUNT ON;

Without this sqlwill return the rowcountfor the call, which will come back without a column name, causing the NoneTypeerror.

如果没有这sql将返回rowcountfor 调用,它将在没有列名的情况下返回,从而导致NoneType错误。

回答by allydh

pd.read_sql()expects to have output to return, and tries to iterate through the output; that's where the TypeErroris coming from. Instead, execute with a cursor object:

pd.read_sql()期望有输出返回,并尝试遍历输出;这TypeError就是来自的地方。相反,使用游标对象执行:

import datetime as dt
import pyodbc
import pandas as pd

conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server Native client 11.0}',server = '*****', database = '**')
cur = conn.cursor()
cur.execute("EXEC ******** '20140528'")

You won't receive any output, but since none is expected, your code should run without error.

您不会收到任何输出,但由于没有任何输出,您的代码应该可以正常运行。

回答by Денис Тимофеев

import datetime as dt
import pyodbc
import pandas as pd

conn = pyodbc.connect('Trusted_Connection=yes; driver =SQL Server Native client 
11.0; server = *****, database = **')
sqlSend = conn.cursor()
sqlSend.execute(f"EXEC ******** '20140528'")
conn.commint()