PostgreSQLのテーブルをCSVで出力

 use Text::CSV_XS;
 use DBI;
 use strict;
 
 my $dsn = "dbi:Pg:dbname=mydb";
 my $user = "taro";
 my $pass = "pass";
 
 my $csv = Text::CSV_XS->new({binary=>1});
 
 my $dbh = DBI->connect($dsn, $user, $pass, {RaiseError=>0,PrintError=>1,AutoCommit=>1}) or die $DBI::errstr;
 my $sql = 'select * from member';
 my $sth = $dbh->prepare($sql);
 $sth->execute();
 
 my @columns = @{$sth->{NAME}};
 $csv->combine(@columns) or die $csv->error_input;
 print $csv->string,"\n";
 
 while (my $row = $sth->fetch){
     $csv->combine(@{$row}) or die $csv->error_input;
     print $csv->string, "\n";
 }
 die $sth->errstr if $sth->err;
 $dbh->disconnect;

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS