我正在尝试替代Python / pandas导出过程,并直接从Oracle转到csv。我看过几篇类似here
的帖子假设我在Oracle中有一个包含三列的表:ColA,ColB,ColC。我想使用一个命令行实用程序,该实用程序将一条SQL命令作为输入,并生成一个CSV文件,该文件看起来像带有标题行和值行的任何标准CSV文件:
ColA,ColB,ColC
A,B,C
D,E,F
...
在SQL Server中,有一个名为bcp的实用程序,我可以使用它,如下所示:
bcp "SELECT 'ColA', 'ColB', 'ColC' UNION ALL Select ColA, ColB, ColC From
myTable" queryout "C:\Temp\csvfiles\output.csv" -c -CRAW -S localhost -u
my_userid -p my_password -d my_database
轻松自在。但是在寻找与Oracle相当的产品时,并没有那么多。
我看了here,但是作者希望您创建一个UTL_FILE。这似乎不太可能,因为这应该是一个完全通用的过程,是从Python构建并运行的。我看了sqlplus,但似乎无法想出一种创建类似于bcp的典型CSV的方法。 here这个文档也不是很清楚。我希望看到的例子是如此普遍。
类似here的站点显示了如何使用sqlplus输出固定长度的CSV,但没有显示如何添加标题行和填充值,这虽然可以,但并不理想。这是我能想到的最好的结果:
set colsep ,
set headsep off
set pagesize 0
set trimspool on
set linesize 200
set numwidth 50
SET TERMOUT OFF
Spool output.csv
SELECT ColA,
ColB,
ColC
FROM MyTable;
Spool off
exit
那么,在Oracle中是否有与可信赖的bcp等效的工具/命令,或者在某处使用sqlplus的示例可以生成类似于上述带有标题行且没有所有前导空格的csv?还是有另一个选择可以从随机Oracle表生成动态CSV文件?还是我坚持使用Python,pyodbc和pandas来获取格式正确的CSV文件? TIA
答案 0 :(得分:1)
Oracle的SQLcl实用程序(命令行可执行文件sql
或sql.exe
)可以帮助您实现它。
这是下载链接SQLcl。它是免费的。
要以CSV格式导出文件,您只需指定
SET SQLFORMAT CSV
如果要使用其他定界符,请使用
SET SQLFORMAT DELIMITED '|'
这是带有标题的示例输出
SQL> select * from employees;
"EMPLOYEE_ID","FIRST_NAME","LAST_NAME","EMAIL","PHONE_NUMBER","HIRE_DATE","JOB_ID","SALARY","COMMISSION_PCT","MANAGER_ID","DEPARTMENT_ID"
198,"Donald","OConnell","DOCONNEL","650.507.9833",21-06-07,"SH_CLERK",2600,,124,50
199,"Douglas","Grant","DGRANT","650.507.9844",13-01-08,"SH_CLERK",2600,,124,50
200,"Jennifer","Whalen","JWHALEN","515.123.4444",17-09-03,"AD_ASST",4400,,101,10
201,"Michael","Hartstein","MHARTSTE","515.123.5555",17-02-04,"MK_MAN",13000,,100,20
202,"Pat","Fay","PFAY","603.123.6666",17-08-05,"MK_REP",6000,,201,20
203,"Susan","Mavris","SMAVRIS","515.123.7777",07-06-02,"HR_REP",6500,,101,40
204,"Hermann","Baer","HBAER","515.123.8888",07-06-02,"PR_REP",10000,,101,70
205,"Shelley","Higgins","SHIGGINS","515.123.8080",07-06-02,"AC_MGR",12008,,101,110
206,"William","Gietz","WGIETZ","515.123.8181",07-06-02,"AC_ACCOUNT",8300,,205,110
100,"Steven","King","SKING","515.123.4567",17-06-03,"AD_PRES",24000,,,90
101,"Neena","Kochhar","NKOCHHAR","515.123.4568",21-09-05,"AD_VP",17000,,100,90
102,"Lex","De Haan","LDEHAAN","515.123.4569",13-01-01,"AD_VP",17000,,100,90
103,"Alexander","Hunold","AHUNOLD","590.423.4567",03-01-06,"IT_PROG",9000,,102,60
104,"Bruce","Ernst","BERNST","590.423.4568",21-05-07,"IT_PROG",6000,,103,60
105,"David","Austin","DAUSTIN","590.423.4569",25-06-05,"IT_PROG",4800,,103,60
106,"Valli","Pataballa","VPATABAL","590.423.4560",05-02-06,"IT_PROG",4800,,103,60
107,"Diana","Lorentz","DLORENTZ","590.423.5567",07-02-07,"IT_PROG",4200,,103,60
108,"Nancy","Greenberg","NGREENBE","515.124.4569",17-08-02,"FI_MGR",12008,,101,100
109,"Daniel","Faviet","DFAVIET","515.124.4169",16-08-02,"FI_ACCOUNT",9000,,108,100
此外,所有SQL * Plus命令均受支持,而很少有特定于SQLcl的命令。查看此command line reference
答案 1 :(得分:0)
SET MARKUP CSV ON-在执行查询以csv格式获取数据之前,在sqlplus中使用它