2011/10/27

selectall_arrayref vs. selectall_hashref

Both selectall_arrayref and selectall_hashref are method that combines "prepare", "execute" and "fetchall_arrayref" into a single call. The former returns a reference to an array containing a reference to an array (or hash, see below) for each row of data fetched. And the latter returns a reference to a hash containing one entry, at most, for each row, as returned by fetchall_hashref(). Note that selectall_hashref return the ordered list of result as statement intented to, for example,
$sql = \"select ename from employee order by ename\"; 
$hash_ref = $dbh->selectall_hashref($statement, \"ename\");
The %$hash_ref does not contant the ordered list of ename, because it's hash. So the get the ordered list, you need to sort the hash. like
sort(%$hash_ref);
In some case, the statement has "order by" multiple fields, it's not easy to sort hash to having the same order as statement trying to, so you may just use selectall_arrayref, which can also return a reference to a hash, for example,
$sql = \"select ename, eage from employee order by ename, eage\";
my $emps = $dbh->selectall_arrayref(
      $sql,
      { Slice => {} }
  );
  foreach my $emp ( @$emps ) {
      print \"Employee: $emp->{ename}\n\";
  }
For more perl dbi usage, click here http://search.cpan.org/~timb/DBI/DBI.pm

No comments:

Post a Comment