Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: From database to hash table

by choroba (Abbot)
on Sep 06, 2012 at 16:58 UTC ( #992146=note: print w/ replies, xml ) Need Help??


in reply to From database to hash table

There is no builtin, but there is DBI:

#!/usr/bin/perl use warnings; use strict; use DBI; use Data::Dumper; my $db = DBI->connect("dbi:$driver:", q(), q()); my %hash; my $sth = $db->prepare('select week, month, workperiod from tablename' +); $sth->execute; while (my ($week, $month, $workperiod) = $sth->fetchrow_array) { $hash{$week} = [$month, $workperiod]; } print Dumper \%hash;
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: From database to hash table
Download Code
Re^2: From database to hash table
by Tux (Monsignor) on Sep 06, 2012 at 17:26 UTC

    Faster alternative 1:

    my %hash; my %rec; my $sth = $db->prepare ("select * from tablename"); $sth->execute; $sth->bind_columns (\@hash{@{$sth->{NAME_lc}}}); while ($sth->fetch) { $hash{$rec{week}} = [ $rec{month}, $rec{workperiod} ]; }

    Faster alternative 2:

    my %hash; my $sth = $db->prepare ("select week, month, workperiod from tablename +"); $sth->execute; $sth->bind_columns (\my ($week, $month, $workperiod)); while ($sth->fetch) { $hash{$week} = [ $month, $workperiod ]; }

    Readabler alternative 3:

    my $dbh = DBI->connect ("dbi:$driver:", "user", "pass", { FetchHashKey +Name => "NAME_lc" }); my %hash; my $sth = $db->prepare ("select week, month, workperiod from tablename +"); $sth->execute; while (my $rec = $sth->fetchrow_hashref) { $hash{$rec->{week}} = [ $rec->{month}, $rec->{workperiod} ]; }

    Enjoy, Have FUN! H.Merijn

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2014-11-28 00:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (191 votes), past polls