Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Re: Field names from DBI?

by cchampion (Curate)
on Jun 10, 2003 at 14:01 UTC ( [id://264676]=note: print w/replies, xml ) Need Help??


in reply to Re: Field names from DBI?
in thread Field names from DBI?

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.

Replies are listed 'Best First'.
Re: Re: Re: Field names from DBI?
by barrd (Canon) on Jun 10, 2003 at 14:15 UTC
    Thanks cchampion,

    Cool, didn't know that... hmmm, /me "thinks have to go redo some code now". I've been working on a bit of code with a friend to 'clone' an SQL table row, you've just given me a couple of very valuable ideas for improvement... thanks again!

    barrd

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://264676]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-03-28 17:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found