sid_com
sid_com

Reputation: 25157

How to get the column-names from DBD::CSV?

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.

Upvotes: -1

Views: 1672

Answers (1)

btilly
btilly

Reputation: 46542

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.

Upvotes: 6

Related Questions