如何使用DBD :: CSV手动指定列名?

时间:2012-10-22 17:42:36

标签: perl csv dbd

我正在使用DBD::CSV来显示csv数据。有时文件不包含列名,因此我们必须手动定义它。但在我按照文档后,我不知道如何使属性skip_first_row工作。我的代码是:

#! perl
use strict;
use warnings;
use DBI;

my $dbh = DBI->connect("dbi:CSV:", undef, undef, {
    f_dir            => ".",
    f_ext            => ".txt/r",
    f_lock           => 2,
    csv_eol          => "\n",
    csv_sep_char     => "|",
    csv_quote_char   => '"',
    csv_escape_char  => '"',
    csv_class        => "Text::CSV_XS",
    csv_null         => 1,
    csv_tables       => {
        info => {
            file => "countries.txt"
        }
    },  
    FetchHashKeyName => "NAME_lc",
}) or die $DBI::errstr;

$dbh->{csv_tables}->{countries} = {
  skip_first_row => 0,
  col_names => ["a","b","c","d"],
};

my $sth = $dbh->prepare ("select * from countries limit 1");
$sth->execute;
while (my @row = $sth->fetchrow_array) {
  print join " ", @row;
  print "\n"
}
print join " ", @{$sth->{NAME}};

countries.txt文件是这样的:

AF|Afghanistan|A|Asia
AX|"Aland Islands"|E|Europe
AL|Albania|E|Europe

但是当我运行这个脚本时,它会返回

AX Aland Islands E Europe
AF AFGHANISTAN A ASIA

我预计它会返回:

AF AFGHANISTAN A ASIA
a b c d

a b c d
a b c d

有谁知道这里发生了什么?

1 个答案:

答案 0 :(得分:0)

出于某种原因,与文档相反,除非您将它们传递给connect,否则它不会看到每个表的设置。

my $dbh = DBI->connect("dbi:CSV:", undef, undef, {
    f_dir            => ".",
    f_ext            => ".txt/r",
    f_lock           => 2,
    csv_eol          => "\n",
    csv_sep_char     => "|",
    csv_quote_char   => '"',
    csv_escape_char  => '"',
    csv_class        => "Text::CSV_XS",
    csv_null         => 1,
    csv_tables       => {
        countries => {
            col_names => [qw( a b c d )],
        }
    },
    FetchHashKeyName => "NAME_lc",
}) or die $DBI::errstr;

然后它工作正常:

my $sth = $dbh->prepare ("select * from countries limit 1");
$sth->execute;

print "@{ $sth->{NAME} }\n";      # a b c d

while (my $row = $sth->fetch) {
    print "@$row\n";              # AF Afghanistan A Asia
}