Qiang has asked for the wisdom of the Perl Monks concerning the following question:

hello,

using DBI and Template Toolkit.

my webapp needs to fetch 100-300 rows with 5-6 columns and display them using Template. i don't want to reference each col by index from my template so i chose to fetch hashref. what i have is something like:

my $sth = $dbh->prepare_cached( $sql ); $sth->execute( @bind_vals ); $result = $sth->fetchall_hashref( $name ); $tt->process("result.tt", { result => $result })
but knowing that fetchall_hashref being the slowest among fetchall_arrayref and fetchrow_arrayref. i tried to use bind_columns and fetchrow_arrayref :
my ( %row , @rows ); $sth->bind_columns( \( @row{ @{$sth->{NAME_lc}} } ) ); while ( $sth->fetchrow_arrayref ) { my %row_copy = %row; push @rows, \%row_copy; } $tt->process("result.tt", { result => \@rows })
i got all result in nice AoH structure. but that defeats the purpose of bind_columns.

the DBI example of using bind_columns are fine as it prints out the fetched result in each loop. I can't do that and still use my template.

so my question is how do you use bind_columns with Template that require you to collect all results first?

UPDATE: my last sentence is bit misleading. i am wondering if there are better way to achive the same goal?

Replies are listed 'Best First'.
Re: DBI output and Template Toolkit
by ikegami (Patriarch) on Mar 23, 2007 at 16:14 UTC

    so my question is how do you use bind_columns with Template that require you to collect all results first?

    You're already doing it.

    A couple of quick notesnits:

    • my %row_copy = %row; push @rows, \%row_copy;
      is the same as
      push @rows, { %row };
    • When I use bind_columns, I find using

      while ( $sth->fetchrow_arrayref ) {

      to be somewhat misleading since there's no array_ref involved. Instead, I use

      while ( $sth->fetch ) {

      fetch and fetchrow_arrayref are the same function.