Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Retrieving column names from SQL with DBI

by hippo (Bishop)
on Sep 25, 2020 at 08:35 UTC ( [id://11122192]=note: print w/replies, xml ) Need Help??


in reply to Retrieving column names from SQL with DBI

If you use a hashref as the slice arg to fetchall_arrayref you will receive an AoH rather than an AoA. Then it becomes trivial:

my $query = $connect->prepare ("SELECT * FROM TableName"); $query->execute (); my $data = $query->fetchall_arrayref ({}); for my $row (@$data) { for my $key (keys %$row) { print "Column name is $key, column value is $row->{$key}\n"; } }

🦛

Replies are listed 'Best First'.
Re^2: Retrieving column names from SQL with DBI
by Tux (Canon) on Sep 25, 2020 at 09:16 UTC

    Note that fetching hashrefs is (much) slower than fetching arrayrefs. Most often this is marginal compared to the time spent in getting the data from the database, but in many cases, you can bring the speed back by using bind_columns:

    my $sth = $dbh->prepare ("select * from foo"); $sth->execute; my (@fields, %r) = @{$sth->{NAME_lc}}; $sth->bind_columns (\@r{@fields}); while ($sth->fetch) { # Do something with the record. Fields are stored in %r printf "%-16s: %s\n", $_, $r{$_} // "--undef--" for @fields; }

    Enjoy, Have FUN! H.Merijn
Re^2: Retrieving column names from SQL with DBI
by Krillian (Acolyte) on Sep 25, 2020 at 18:42 UTC
    Dear all, Thank you very much for all your suggestions. Went with fetchall_arrayref for now and does exactly what I need. Will try out the other solutions later as well. Again, thank you!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-03-29 02:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found