How to combine MySQL queries looped over different databases into one excel file (append the resulting dataframes)

I am new to python. I had a friend help me with this code which pulls up the list of mySQL database names and checks if that same name is in a csv file I called “brokers_list”. If the database name is in the csv file, it executes a policies and users query from mySQL, adds in an extra column with that database name and exports it into excel as a separate file for each database with each query (policies and users) as sheets in that workbook.

I am trying to change the last part of this python code so that instead of having a different workbook for each database with the queries as sheets, I want one workbook where all the databases results are appended under each query as a sheet. For example I want one workbook and under the policies sheet it would have the mySQL query for all the databases not just one. Basically appending the results from each query’s database into one table for the policies table and the users table where they remain as table sheets. Here is the code concerning this task:

#Get broker list from the csv file

brokers_list = get_brokers() for databasename in available_databases: print(‘available database—>>’, databasename[0])

if(databasename[0] in brokers_list): # check if the broker name exist in database list
  use_q = engine.execute('USE {}'.format(databasename[0]))
  with engine.connect() as con:
    policies = get_policies(con) # execute sql query to get policies
    users = get_users(con) # # execute sql query to get users
    #start writing data into files
    policies_df = pd.DataFrame(policies, columns =['id', 'policyNumber', 'LineOfBusinessCode'])
    users_df = pd.DataFrame(users, columns =['id', 'name', 'email'])
    policies_df.insert(0, 'broker_name', databasename[0])
    users_df.insert(0, 'broker_name', databasename[0])
    # write all sheet in one excel file
    with pd.ExcelWriter('{}_result.xlsx'.format(databasename[0])) as writer:
      policies_df.to_excel(writer, sheet_name='policies')
      users_df.to_excel(writer, sheet_name='users')