所以我在本地 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/