【问题标题】:How to manually specify the column names using DBD::CSV?如何使用 DBD::CSV 手动指定列名?
【发布时间】:2012-10-23 02:20:56
【问题描述】:

我正在使用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}};

country.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

有人知道这里发生了什么吗?

【问题讨论】:

  • 感谢您指出我更正了问题。
  • 让我进一步完善我的问题以使其清楚。

标签: perl csv dbd


【解决方案1】:

由于某种原因,与文档相反,它看不到每个表的设置,除非您将它们传递给 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
}

【讨论】:

  • 我更新了我的答案以匹配更新后的问题。 (仅出于视觉原因,我使用 fetch 而不是 fetchrow_arrayref。)
  • skip_first_row => 0在使用col_names时是多余的,所以我没有使用。
猜你喜欢
  • 1970-01-01
  • 2011-08-12
  • 2021-07-26
  • 2011-02-16
  • 2015-01-19
  • 1970-01-01
  • 2022-12-10
  • 2011-02-17
  • 1970-01-01
相关资源
最近更新 更多