[英]How to manually specify the column names using DBD::CSV?
I am using DBD::CSV to show csv data. 我正在使用DBD :: CSV显示CSV数据。 Sometimes the file doesn't contain column names, so we have to manually define it.
有时文件不包含列名,因此我们必须手动定义它。 But after I followed the documentation, I got stuck with how to make the attribute skip_first_row work.
但是,在遵循了文档之后,我陷入了如何使属性skip_first_row工作的困扰。 The code I have is:
我的代码是:
#! 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}};
The countries.txt file is like this: country.txt文件如下所示:
AF|Afghanistan|A|Asia
AX|"Aland Islands"|E|Europe
AL|Albania|E|Europe
But when I ran this script, it returns 但是当我运行此脚本时,它会返回
AX Aland Islands E Europe
AF AFGHANISTAN A ASIA
I expected it to either return: 我希望它会返回:
AF AFGHANISTAN A ASIA
a b c d
or 要么
a b c d
a b c d
Does any know what's going on here? 有谁知道这是怎么回事吗?
For some reason, contrary to the documentation, it doesn't see the per-table settings unless you pass them to connect
. 由于某种原因,与文档相反,除非将它们传递给
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;
Then it works fine: 然后工作正常:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.