Search code examples
sqlcsvperlodbcdbi

Can't select a column from csv file


I use Perl to connect to a DBD::CSV with DBI, the connection works well and when I launch

SELECT * FROM dp_id.csv 

It works fine but when I want to extract a single column.

my $dbh = DBI->connect ("dbi:CSV:", undef, undef, { f_dir => "." });

my $query = " SELECT DpName from dp_id.csv";


my $sth   = $dbh->prepare ($query);
$sth->execute ();

while (my @row = $sth->fetchrow_array)
{
    print @row,"\n";
}

I've this error

 Execution ERROR: No such column 'dpname' called from extract.pl at 20.
 [for Statement " SELECT DpName from dp_id.csv"] at extract.pl line 20.
 DBD::CSV::st fetchrow_array failed: Attempt to fetch row without a preceding execute () call or from 
 a non-SELECT statement [for Statement " SELECT DpName from dp_id.csv"] at extract.pl line 22.

Here is an extract from the csv file:

kindOfInfo;DpName;TypeName;ID
interface;ALLARM;DPT_TS;344108
interface;POMP1;DPT_TS;7923082

Solution

  • By default, DBD::CSV assumes that your files are comma separated (because that's what the "CS" in CSV stands for :-))

    Your data is separated by semicolons. So you need to tell DBD::CSV that when creating the connection.

    my $dbh = DBI->connect ("dbi:CSV:", undef, undef, {
      f_dir        => ".",
      csv_sep_char => ';', # This is the important line
    });
    

    Without that, the DBD sees your data as single column with the name "kindOfInfo;DpName;TypeName;ID".