简体   繁体   中英

How do I read SQL stored procedure data through pyodbc and get results into a dataframe?

I have a stored proc in SQL Server called test.storedproc

My py script is as follows

import pyodbc
import pandas as pd
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=PMI0x8x\xxx;'
                      'Database=Warehouse;'
                      'Trusted_Connection=yes;'
                      )

cmd_prod_executesp = """EXEC Test.storedproc"""
cursor = conn.cursor()
cursor.execute(cmd_prod_executesp)
conn.commit()

This runs successfully. However, how do I get the data which is in the storedproc as a dataframe?I tried -

dfo = pd.read_sql_query(cmd_prod_executesp, conn)
Traceback (most recent call last):

  File "<ipython-input-70-06220d2e8e81>", line 1, in <module>
    dfo = pd.read_sql_query(cmd_prod_executesp, conn)

  File "C:\Users\xx\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 383, in read_sql_query
    chunksize=chunksize,

  File "C:\Users\xx\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1744, in read_query
    columns = [col_desc[0] for col_desc in cursor.description]

TypeError: 'NoneType' object is not iterable

How do I read stored proc data into a dfo?

Not enough rep to comment or I would (since this isn't an explicit answer) but you could use the sp to run the data into a temp table then select * from temp table and then the df = pd.read_sql(sql, con=connection) should work just fine.

If you aren't as handy with sql... here is a topic which shows how to run sp into temp table. link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM