They are not the same thing, though.

Not only fetchrow_hashref will be slower, because the names are assigned for each row, while $sth->{NAME} is only evaluated once, after the call to "execute," but in addition, if your query contains two columns with the same name, $sth->{NAME} will handle it, but fetchrow_hashref will not.

select * from dept; select * from emp; +--------+----------+ | deptID | name | +--------+----------+ | 1 | pers | | 2 | sales | | 3 | research | +--------+----------+ +-------+-------+--------+ | empID | name | deptID | +-------+-------+--------+ | 1 | John | 1 | | 2 | Fred | 2 | | 3 | Susan | 2 | +-------+-------+--------+ select distinct dept.deptID, emp.deptID from dept left join emp using(deptID); +--------+--------+ | deptID | deptID | +--------+--------+ | 1 | 1 | | 2 | 2 | | 3 | NULL | +--------+--------+

Given these tables, the Perl code to handle them could be:

my $query = qq{select distinct dept.deptID, emp.deptID from dept left join emp using(deptID)}; my $sth = $dbh->prepare($query); $sth->execute(); print "--- names\n"; print join ", ", @{$sth->{NAME}}; print "\n--- fetchrow_hashref\n"; my $row = $sth->fetchrow_hashref(); print "$_ \t" for keys %$row; print "\n"; $sth->finish(); __OUTPUT__ --- names deptID, deptID --- fetchrow_hashref deptID

Notice that $sth->{NAME}, despite the double names, returns the correct result. fetchrow_hashref, instead, misses one column altogether.


In reply to Re: Re: Field names from DBI? by cchampion
in thread Field names from DBI? by Massyn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.