Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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] ]; }

Replies are listed 'Best First'.
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.
      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
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;


    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://729416]
Approved by Bloodnok
and the daffodils sway...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2017-12-15 17:15 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (439 votes). Check out past polls.