简体   繁体   English

仅当脚本使用python返回数据时,如何将结果从多个Oracle sql脚本导出到csv

[英]How to export the results from multiple oracle sql scripts to csv only when the script returns data using python

I am new to writing a python code for automation, so my motif is to execute multiple etl testing scripts written in oracle sql and write the result of each query to a csv file, the script has multiple sql queries each query result should be written to a different tab in the csv.. I tried to write a basic structure as below but need help on how I can modify the code below: import os import cx_Oracle import csv 我刚开始编写用于自动化的python代码,因此我的主题是执行多个用oracle sql编写的etl测试脚本,并将每个查询的结果写入csv文件,该脚本具有多个sql查询,每个查询结果都应写入我尝试编写如下的基本结构,但需要有关如何修改以下代码的帮助:import os import cx_Oracle import csv

f = open('tabledefinition.sql') #PATH WHERE THE SQL SCRIPTS ARE STORED

full_sql = f.read()

SQL= full_sql.split(';')

filename="S:\Output.csv" # PATH WHERE THE OUTPUT FILE IS STORED
FILE=open(filename,"w");
output=csv.writer(FILE, dialect='excel')

connection = cx_Oracle.connect('userid/password@99.999.9.99:PORT/SID') 
#CONNECTION DETAILS FOR DB

cursor = connection.cursor()

for sql_command in SQL:
    cursor.execute(SQL)
    for row in cursor:
        output.writerow(row)
        cursor.close()
        connection.close()
        FILE.close() 

Although I haven't tried this myself, these questions make it clear that csv files cannot have multiple sheets/tabs: q1 , q2 , q3 . 尽管我自己还没有尝试过,但是这些问题使csv文件不能包含多个工作表/标签: q1q2q3

I can, however, recommend the use of The Pandas package . 但是,我可以建议使用The Pandas package It has a very handy read_sql function , as well as a, perhaps equally handy, to_csv function . 它具有一个非常方便的read_sql函数以及一个可能同样方便的to_csv函数 The read_sql function will collect the information from your db into a DataFrame object. read_sql函数将从数据库中收集信息到DataFrame对象中。 That Dataframe can then be manipulated or it can be stored in some number of different formats, one of which is csv. 然后可以操纵该数据帧或将其存储为多种不同格式,其中一种就是csv。 If you require multiple sheets in one file, one available option is an hdf file or even an excel (.xlsx) file . 如果在一个文件中需要多个图纸,则一个可用的选项是hdf文件 ,甚至是excel(.xlsx)文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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