in reply to Dereferencing nested references
my $statement = q{ SELECT * FROM BuyersSellers WHERE FileNumber = ? }; #force selectall_arrayref to return an arrayref of hashrefs my %attr = ( dbi_fetchall_arrayref_attr => {}, ); my $BuyersSellers = $dbh->selectall_arrayref($statement, \%attr, $file +number);
The above code replaces the first prepare, execute, fetchrow_hashref block above. It does the same thing, but utilizes DBI's utility method selectall_arrayref.
Placeholders are used, which is what the question marks in the SQL query are. They allow you to substitute values into the SQL query on the fly. DBI even takes care of calling DBI->quote against each value before substituion. That means you don't have to worry about quoting values in the SQL, DBI will figure it out for you. Besides, the SQL code ends up prettier with placeholders than without =). There is an in-depth placeholder explanation here
$statement = q{ SELECT * FROM People WHERE PersonID = ? }; my $sth = $dbh->prepare($statement); foreach my $buysell (@$BuyersSellers) { $sth->execute($buysell->{PersonID}); my $row = $sth->fetchrow_hashref('NAME_lc'); $buysell->{PersonID} = { %$row }; }
Notice that I prepared the statment handle before the loop? Then inside the loop I call execute over and over, getting the matching People record, and assigning it to the $buysell->{PersonID}. Since the $sth handle was prepared using placeholders, the actual value to match PersonID doesn't need to be defined until $sth->execute, where we pass it in at run-time.
With some databases that support placeholders natively, like Oracle, the speed increases can be significant. Worst case you'll get no speed up, but just be left with a tighter loop and cleaner code.
foreach my $buysell (@$BuyersSellers) { next unless $buysell->{BuyerORSeller} eq 'BUYER'; print qq{<tr class="$class"><td>$buysell->{PersonID}->{LastName}</td +></tr>}; }
Then finally, looping through the $BuyerSellers arrayref and printing out the results
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Dereferencing nested references
by ryddler (Monk) on Jan 17, 2001 at 02:44 UTC | |
by btrott (Parson) on Jan 17, 2001 at 03:08 UTC |