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

sid*_*com 0 csv perl columnname dbi

如何从表中获取列名?我的尝试不起作用:

#!/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.
Run Code Online (Sandbox Code Playgroud)

bti*_*lly 6

column_info方法应该由驱动程序实现,undef如果没有,则可以获得.

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

顺便提一下,这DBD::CSV是一个有趣的玩具,但如果你需要一个轻量级的一次性数据库,我强烈推荐使用DBD::SQLite.如果您只需要处理CSV数据,那么有几个不错的模块可以为您提供原始访问权限.在这两者之间,很少有用例留下DBD::CSV很有意义.