如何从 DBD::CSV 获取列名?

发布于 2024-11-03 02:00:47 字数 1103 浏览 1 评论 0原文

如何从表中获取column-names?这不起作用:

#!/usr/bin/env perl
use warnings;
use 5.012;
use DBI;

my $options  = { RaiseError => 1, PrintError => 0, f_ext => ".csv/r" };
my $dbh = DBI->connect( "dbi:CSV:", undef, undef, $options ) or die $DBI::errstr;

my $table = 'test';
$dbh->do( "CREATE TEMP TABLE $table ( id INT, size INT )" );
my $sth = $dbh->prepare( "INSERT INTO $table ( id, size ) VALUES( ?, ? )" );
$sth->execute( 1, 235 );
$sth->execute( 2, 42 );

use Data::Dumper;
say Dumper $dbh->{csv_tables}{$table}{col_names};

$dbh->{csv_tables}{$table} = { skip_first_row => 0 };
$sth = $dbh->prepare( "SELECT * FROM $table" );
$sth->execute;
my @first_row = $sth->fetchrow_array;
say "@first_row\n";

$sth = $dbh->column_info( '', '', $table, '' );
my $ref = $sth->fetchall_arrayref;
say "@$_" for @$ref;

错误:

$VAR1 = undef;

1 235

Can't call method "fetchall_arrayref" on an undefined value at ./so.pl line 25.

How can I get the column-names from the table? This did not work:

#!/usr/bin/env perl
use warnings;
use 5.012;
use DBI;

my $options  = { RaiseError => 1, PrintError => 0, f_ext => ".csv/r" };
my $dbh = DBI->connect( "dbi:CSV:", undef, undef, $options ) or die $DBI::errstr;

my $table = 'test';
$dbh->do( "CREATE TEMP TABLE $table ( id INT, size INT )" );
my $sth = $dbh->prepare( "INSERT INTO $table ( id, size ) VALUES( ?, ? )" );
$sth->execute( 1, 235 );
$sth->execute( 2, 42 );

use Data::Dumper;
say Dumper $dbh->{csv_tables}{$table}{col_names};

$dbh->{csv_tables}{$table} = { skip_first_row => 0 };
$sth = $dbh->prepare( "SELECT * FROM $table" );
$sth->execute;
my @first_row = $sth->fetchrow_array;
say "@first_row\n";

$sth = $dbh->column_info( '', '', $table, '' );
my $ref = $sth->fetchall_arrayref;
say "@$_" for @$ref;

Error:

$VAR1 = undef;

1 235

Can't call method "fetchall_arrayref" on an undefined value at ./so.pl line 25.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪是无色的血 2024-11-10 02:00:47

column_info 方法应该由驱动程序实现,如果尚未实现,您将得到 undef

相反,我会在执行第一个查询后查看 $sth->{NAME}

顺便说一句,DBD::CSV 是一个有趣的玩具,但如果您需要一个轻量级的一次性数据库,我强烈建议使用DBD::SQLite。如果您只需要处理 CSV 数据,有几个不错的模块可以为您提供原始访问权限。在这两者之间,DBD::CSV 有意义的用例非常少。

The column_info method is supposed to be implemented by the driver, and you get undef if it has not been.

Instead I'd look at $sth->{NAME} after you executed the first query.

Incidentally DBD::CSV is a fun toy, but if you need a lightweight throwaway database I strongly recommend using DBD::SQLite instead. And if you just need to handle CSV data, there are several decent modules out there that give you raw access. Between those two, there are very few use cases left where DBD::CSV makes much sense.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文