8
votes

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

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

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.

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
3
Can you post the full error code? - SuperBiasedMan
are certain that your query is valid? what's different about this block of code than the others that work? - Paul H
I can see a lot of unmatched closing quotes for strings ", '? - ZdaR
Can you show the output of directly doing conn.execute("EXEC ..") and then fetchall() ? Are you sure it returns anything? - joris
package are able to handle sql NULL, most likely is some error in your query. If you're using microsoft sql server have a look at mssql package which works without setting up odbc connecting :) - Alessandro Mariani

3 Answers

20
votes

Your sproc needs

SET NOCOUNT ON;

Without this sql will return the rowcount for the call, which will come back without a column name, causing the NoneType error.

4
votes

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

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.

0
votes
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()