Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
P is for Practical
 
PerlMonks  

From database to hash table

by Anonymous Monk
on Sep 06, 2012 at 16:47 UTC ( #992143=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have to fetch data from database using the statement "Select s_week,s_month,s_workperiod from <tablename>".I need to write the output into a hashtable with s_week as key to that hastable.Can anyone please help me since i m a beginner in Perl?

.. I know how to fetch from database and then write into hash.But is there any inbuilt function for this purpose??

Comment on From database to hash table
Re: From database to hash table
by choroba (Abbot) on Sep 06, 2012 at 16:58 UTC
    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;
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      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
Re: From database to hash table
by runrig (Abbot) on Sep 06, 2012 at 19:21 UTC
    If you want a reference to a HoH:
    my $href = $dbh->selectall_hashref(<<SQL, 's_week'); select s_week,s_month,s_workperiod from <tablename> SQL

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://992143]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2014-04-18 22:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (472 votes), past polls