Python Pandas read_sql_query “'NoneType' object is not iterable” error

浪尽此生 提交于 2019-12-23 09:51:39

问题


I am trying to execute a sql and save a result into Panda Dataframe. here is my code.

        dbserver = 'validserver'
        filename = 'myquery.sql'
        database  ='validdb'       
        conn = pyodbc.connect(r'Driver={SQL Server};Server=' + dbserver + 
            ';Database=' + database + ';Trusted_Connection=yes;')
        fd = open(filename, 'r')
        resultingData = pd.read_sql_query(fd.read(),conn)
        fd.close()
        conn.close()

line pd.read_sql_query(fd.read(),conn) continues to give me error 'NoneType' object is not iterable” error

I can run myquery.sql in a sql server window with results. I do have SET NOCOUNT ON;

Any clue what am I missing here and how do I debug this? myquery.sql has few #temp tables and joins. Result has about 75k rows. Thanks all.

Update:

I can not post the exact query but this is how query looks like.

SET NOCOUNT ON;

SELECT SourceID, PeriodEndDate = MAX(PeriodEndDate)
INTO #SourceDate 
FROM table1
WHERE PERIODENDDATE <= 20171229
GROUP BY SourceID

SELECT RS.*, R.TypeCode INTO #final
FROM table2 RS
INNER JOIN #SourceDate SD ON SD.id = RS.id
INNER JOIN table3 R ON R.id = RS.id

select * from #final

回答1:


From what I understand, read_sql_query() would only return the results from your first statement anyhow. In which case, it's SET NOCOUNT ON; and as you can see, will return None, which is why your code failed. IMO You should be optimizing your SQL statement to return one table instead of multiple in the process (as you only want to read from #final I assume).

If you really want to have multiple sql query in a dataframe, you can use lists and split as mentioned in this thread:

Pandas read_sql query with multiple selects



来源:https://stackoverflow.com/questions/48287404/python-pandas-read-sql-query-nonetype-object-is-not-iterable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!