简体   繁体   中英

execute multiple queries in a location

I have two sql queries[query1][query2] which contains all the fields from two different tables in a database. I need to convert these sql queries to two different csv files and store it in a specific location. I expect the output file to be table1.csv, table2.csv.

My existing query converts only one of the queries to a csv format. How can i replicate this with multiple queries?.

query1 = """

SELECT * FROM [TN_TN].[table1]
"""
data = pd.read_sql(query1, cnxn)
cs= data.to_csv(sep=';',index=False)

save_path = 'O:/Bonus/test'
file_name = "table1.csv"

completeName = os.path.join(save_path, file_name)
file1 = open(completeName, "w")
file1.write(cs)
file1.close()

You could add your queries in a list and iterate over them

queries = [query1, query2]

for i, query in enumerate(queries):
    data = pd.read_sql(query, cnxn)
    save_path = 'O:/Bonus/test'
    file_name = f"table{i}.csv"
    completeName = os.path.join(save_path, file_name)
    data.to_csv(completeName, sep=';',index=False)


        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM