Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Perl::DBI - return column header

by iphony (Acolyte)
on Dec 10, 2008 at 14:04 UTC ( #729416=perlquestion: print w/ replies, xml ) Need Help??
iphony has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, Is it possible for Perl::DBI (Oracle) to return the name of the column header each time I run a "select ..." query? I ca'nt find any way to do that easily. Below are a sample of a code which I always use to run select statement. Thanks.
$dbh = DBI->connect ( "dbi:Oracle:host=$ip;sid=$sd;port=1521", $id, $p +w, {RaiseError => 1, AutoCommit => 0} ); my $sqlexe = $dbh->prepare( $sql ); my @tempdata; my @data; $sqlexe->bind_columns ( undef, \$tempdata[0][0], \$tempdata[0] +[1] ); while ( $sqlexe->fetch() ) { push @{@data}, [ $tempdata[0][0], $tempdata[0][1] ]; }

Comment on Perl::DBI - return column header
Download Code
Re: Perl::DBI - return column header
by Corion (Pope) on Dec 10, 2008 at 14:08 UTC

    See DBI, about "Statement handle attributes". The usual approach to getting the column names for a statement is to ->execute it with an additional WHERE 1 = 0 clause.

Re: Perl::DBI - return column header: Yes, fetchrow_hashref
by Narveson (Chaplain) on Dec 10, 2008 at 15:30 UTC

    Use either fetchrow_hashref or selectrow_hashref and extract the keys.

    my $hashref = $sqlexe->fetchrow_hashref(); my @column_names = keys %$hashref;

    Update

    My vote is for the NAME attribute of the statement handle (next reply). Thanks, pfaut.

    If, like me, you've been indoctrinated into thinking that a class's interface should consist solely of methods, you'll miss a lot of good stuff that DBI makes available in the form of attributes.

Re: Perl::DBI - return column header
by pfaut (Priest) on Dec 10, 2008 at 15:51 UTC

    After you execute the statement, the statement handle should contain a NAME attribute. This is a reference to an array containing the names of the columns returned. $sth->{NAME}[$i] will give you the name of column $i. See perldoc DBI.

    90% of every Perl application is already written.
    dragonchild
      Incase if we are not aware of the row header name or it's in the huge size 100 rows that doesn't make it a sense . correct ? So those cases how we neeed to handle it

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://729416]
Approved by Bloodnok
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-09-21 09:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls