python - Pandas IO SQL 和具有多个结果集的存储过程

标签 python sql-server pandas stored-procedures pandasql

所以我在本地 sql server 上有一个存储过程,它返回多个数据集/表

通常,在 python/pyodbc 中我会使用

cursor.nextset()
subset1 = cursor.fetchall()
cursor.nextset()
subset2 = cursor.fetchall()

我希望使用 ps.io.sql.read_sql 并将具有多个结果集的存储过程返回到数据帧中,但是我找不到任何引用如何移动光标并在关闭之前获取更多信息的内容关闭。

import pandas as ps

query = "execute raw.GetDetails @someParam = '118'"
conn = myConnection() #connection,cursor

results = ps.io.sql.read_sql(query, con=conn[0])

results.head()

conn[1].close()

最佳答案

以下应该有效:

import pandas as pd
from sqlalchemy import create_engine

engine = create_engine('mysql://{}:{}@{}/{}'.format(username, password, server, database_name))
connection = engine.connect().connection
cursor = self.connection.cursor()

cursor.execute('call storedProcName(%s, %s, ...)', params)

# Results set 1
column_names = [col[0] for col in cursor.description] # Get column names from MySQL

df1_data = []
for row in cursor.fetchall():
    df1_data.append({name: row[i] for i, name in enumerate(column_names)})

# Results set 2
cursor.nextset()
column_names = [col[0] for col in cursor.description] # Get column names from MySQL

df2_data = []
for row in cursor.fetchall():
    df2_data.append({name: row[j] for j, name in enumerate(column_names)})

cursor.close()

df1 = pd.DataFrame(df1_data)
df2 = pd.DataFrame(df2_data)

编辑:我更新了此处的代码以避免必须手动指定列名。

请注意,原始问题仅指定了“本地 SQL 服务器”,而不是特定类型的 SQL 服务器。这个答案适用于 MySQL,但我没有用任何其他版本测试过它。

关于python - Pandas IO SQL 和具有多个结果集的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627048/

相关文章:

sql - 外主键插入(增量问题)

sql - 为数字编写 SQL 约束脚本使其落在某个范围内?

python - 如何通过正则表达式过滤 Pandas 中的行

Python:无法在我的代码中找到错误。 os.walk() 返回的文件名

Python Pandas,仅重采样特定时间

python - 如何在 Python 和 Postgres 中处理批量数据库导入中的重音字符

SQL Server 2005 混合模式身份验证

Python pandas - 构建多元数据透视表以显示 NaN 和非 NaN 的计数

pandas - 属性错误 : module 'pandas' has no attribute 'read_xml' or 'to_xml'

python - 如何实现粒子引擎