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

  • 本文关键字:何使用 DBD CSV 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}};

国家/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

是否知道这里发生了什么?

出于某种原因,与文档相反,除非将其传递给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 "@$rown";              # AF Afghanistan A Asia
}

最新更新