我正在尝试使用20个不同的表输出执行存储过程。这些输出范围为3-6列和10-100行。如果不是pyodbc,我怎么能在没有相同结构的情况下迭代所有这些表呢?
connection = pyodbc.connect(r'DRIVER={SQL Server Native Client
11.0};SERVER=dsdrsossql2;DATABASE=TableauDev;Trusted_Connection=yes;')
sql = "{call dbo.DGGrading}"
cur = connection.cursor()
rows = cur.execute(sql,).fetchall()
columns = [column[0] for column in cur.description]
df = pd.DataFrame.from_records(rows,columns=columns)
print(df)
答案 0 :(得分:2)
考虑使用数据框列表并使用nextset()
访问多个结果集:
cur = connection.cursor()
df_list = []
# FIRST RESULTSET
rows = cur.execute(sql).fetchall()
columns = [column[0] for column in cur.description]
df_list.append(pd.DataFrame.from_records(rows, columns=columns))
print(df.head())
# SUBSEQUENT RESULTSETS
while (cur.nextset()):
columns = [column[0] for column in cur.description]
df_list.append(pd.DataFrame.from_records(rows, columns=columns))
print(df.head())
cur.close()
# RUN ANY DATAFRAME OPERATION BY EACH ITEM OF df_list
df_list[[1]].describe()
df_list[[2]].head()
df_list[[3]].tail()
df_list[[4]].dtypes
df_list[[5]].columns
答案 1 :(得分:0)
Parfait的代码对我不起作用,因为“后续结果集”缺少一行代码来提取下一张表。我没有足够的意见要发表,所以这是对我有用的代码。
一些其他事情
param1 = "dynamic parameter1"
param2 = "dynamic parameter2"
sql = f"EXEC dbo.StoredProcedure '{param1}', '{param2}'"
cur = cnxn.cursor()
df_list = []
# get First result
rows = cur.execute(sql).fetchall()
columns = [column[0] for column in cur.description]
df_list.append(pd.DataFrame.from_records(rows, columns=columns))
# check for more results
while (cur.nextset()):
rows = cur.fetchall()
columns = [column[0] for column in cur.description]
df_list.append(pd.DataFrame.from_records(rows, columns=columns))
cur.close()