oracle 将 sql 查询导出到 csv 的 Perl 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10856943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 00:52:35  来源:igfitidea点击:

Perl script to export sql query to csv

sqlperloraclecsv

提问by Scuba_Steve

The code below works, but all of the data displays in one row(but different columns) when opened in Excel. The query SHOULD display the data headings, row 1, and row 2. Also, when I open the file, I get a warning that says "The file you are trying to open,'xxxx.csv', is in a different format than specified by the file extension. Verify that the file is not corrupted...etc. Do you want to open the file now?" Anyway to fix that? That may be the cause too.

下面的代码有效,但在 Excel 中打开时,所有数据都显示在一行(但不同的列)中。查询应该显示数据标题、第 1 行和第 2 行。此外,当我打开文件时,我收到一条警告说“您正在尝试打开的文件‘xxxx.csv’的格式与” 无论如何要解决这个问题?这也可能是原因。

tldr; export to csv with multiple rows - not just one. fix Excel error. Thanks!

tldr; 导出到多行的 csv - 不仅仅是一行。修复Excel错误。谢谢!

#!/usr/bin/perl
use warnings;
use DBI;
use Text::CSV;


# local time variables
($sec,$min,$hr,$mday,$mon,$year) = localtime(time);
$mon++;
$year += 1900;

# set name of database to connect to
$database=MDLSDB1;

# connection to the database
my $dbh = DBI->connect("dbi:Oracle:$database", "", "")
or die "Can't make database connect: $DBI::errstr\n";

# some settings that you usually want for oracle 10 
$dbh->{LongReadLen} = 65535; 
$dbh->{PrintError} = 0;  

# sql statement to run
$sql="select * from eg.well where rownum < 3";

my $sth = $dbh->prepare($sql);
$sth->execute();


my $csv = Text::CSV->new ( { binary => 1 } )             
or die "Cannot use CSV: ".Text::CSV->error_diag (); 

open my $fh, ">:raw", "results-$year-$mon-$mday-$hr.$min.$sec.csv"; 

$csv->print($fh, $sth->{NAME});

while(my $row = $sth->fetchrow_arrayref){      

$csv->print($fh, $row);
}

close $fh or die "Failed to write CSV: $!"; 

回答by mawburn

while(my $row = $sth->fetchrow_arrayref){   
  $csv->print($fh, $row);
  $csv->print($fh, "\n");
}

CSV rows are delimited by newlines. Just simply add a newline after each row.

CSV 行由换行符分隔。只需简单地在每一行后添加一个换行符。

回答by Joe

I think another solution is to use the instantiation of the Text::CSVobject and pass along the desired line termination there...

我认为另一个解决方案是使用Text::CSV对象的实例化并在那里传递所需的行终止......

my $csv = Text::CSV->new ( { binary => 1 } )             
  or die "Cannot use CSV: " . Text::CSV->error_diag();

becomes:

变成:

my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" })
  or die "Cannot use CSV: " . Text::CSV->error_diag();