On Monday, January 12, 2004, at 11:37 , Dan Sugalski wrote:

At 4:07 PM +0000 1/12/04, Harry Jackson wrote:
Dan Sugalski wrote:

Well...


What I'd like, I think, is something simple and straightforward. Right now we've got to fetch each column for each row one by one, which is a pain in the neck if you want to get a full row back. Having a fetchrow that returned an Array with the value for column one in the 0th slot, column 2 in the 1st slot and so on would be about 80% of the solution.

I have done this part.



Having a fetchrow_hash that returned a Hash where the keys are the column names and the values are the column values would be most of the rest.

I read somewhere that accessing a hash was slightly slower than accessing and array which is one reason why I never used it. The other reason is that if I name the fileds in the hash then the user needs to know the names to access them or perform some magic to get them. With an array they come out in the order they are aksed for.

Definitely. However... Having seen code in production, generally the fields aren't changeable and are known at compile-time, or folks are writing generic code (for better or worse). In the first case people use hash access because they know there's a "name" and "city" field in the results, and in the second case they're iterating across the keys and pulling out values.


Since folks are going to wrap the results in a hash regardless of whether it's a good idea or not (not going there... :) we might as well have it in at the very lowest level where we can get the information most efficiently.

fetchrow_hashref is definitely a very useful, but my favorite (and also the most efficient) DBI methodology is bind_columns. DBI maintains a list of references corresponding to columns in the result set, and when the result set is advanced, stores the values into the variables referenced. e.g., Perl 5:


        my $sth = $dbh->prepare("select a, b, c from tab");
        $sth->execute;
        $sth->bind_columns(\my($a, $b, $c));
        
        while ($sth->fetch) {
                print "a: $a, b: $b, c: $c\n";
        }

Equivalent to:

        my $sth = $dbh->prepare("select a, b, c from tab");
        $sth->execute;
        $sth->bind_col(0, \my $a);
        $sth->bind_col(1, \my $b);
        $sth->bind_col(2, \my $c);
        
        while ($sth->fetch) {
                print "a: $a, b: $b, c: $c\n";
        }

So if you're going to basically go all out in emulating DBI's fetch_* permutations, don't forget this one. :)



Gordon Henriksen
[EMAIL PROTECTED]

Reply via email to