I'm using the code below to run 3 different queries in 3 different DB's And trying to export them to a single Excel file each result on a different sheet (9 total sheets).
But when running the code below I'm getting a file with only 3 sheets (each contain only the first query result on each DB)
I'm using pyodbc for the DB connection and pandas in order to handle the Excel writing.
databases = {DB1, DB2, DB3}
queries = {query1, query2, query3}
writer = pd.ExcelWriter('C:\Temp\Output.xlsx')
for database in databases:
cnxn = pyodbc.connect(driver='{SQL Server}',
host=database.server,
database=database.db_name,
trusted_connection=database.trusted_connection,
user=database.user_name,
password=database.password)
cursor = cnxn.cursor()
for q in queries:
cursor.execute(q)
rows = cursor.fetchall()
df = pd.read_sql_query(q, cnxn)
df.to_excel(writer,
sheet_name=str(q.index(q))+"-"+database.name)
writer.save()
cursor.executeand thenrows = cursor.fetchall()- why do you then usepd.read_sql_query(executing the query again) instead of feeding the previous stuff straight into a DataFrame?str(q.index(q))this always give 0 , so are u getting sheets 0_DBNAME