perlbeginner
perlbeginner

Reputation: 33

Perl: Store column from Mysql-table in Perl-Hash

I am having Problems with Mysql and Perl.

I am coding a Web-Crawler and I'm saving the TODO-List in a Mysql table.

Now, at the beginning of the Script, I want to load the TODO-List from Mysql into a Perl Hash so that I don't recrawl urls.

Table "todo" - Unique Id "todoid" - the TODO-urls "todourl"

my %todo = ( );

$VAR1 = 'http://www.example.com/661/';

How can I load all the Urls of the Mysql-table in my todo hash?

Upvotes: 1

Views: 1520

Answers (3)

Max Lybbert
Max Lybbert

Reputation: 20021

Class::DBI will do the querying and conversion for you. However, I believe DBIx::Class is more popular right now.

Upvotes: 1

Miguel Prz
Miguel Prz

Reputation: 13792

you can use DBI, like Alan suggested, but with less code:

$todo = $dbh->selectall_hashref('SELECT todoid, todourl FROM todo', 'todoid');

As you can see, I didn't use dbi prepare, execute, fetch and finish, because selectall_hashref method does it all for us.

See the online documentation: http://search.cpan.org/~timb/DBI-1.616/DBI.pm#selectall_hashref

Upvotes: 3

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74202

Connect to the database using DBI, prepare query, execute the query and fetch the results:

#!/usr/bin/env perl

use strict;
use warnings;

use DBI;

my %db_config = (
    'database' => 'your_database_name',
    'hostname' => 'your_hostname',
    'port'     => 'your_port',
    'username' => 'your_username',
    'password' => 'your_password',
);
my $dbh = DBI->connect(
   "DBI:mysql:database=$db_config{database};host=$db_config{hostname};port=$db_config{port}",
    $db_config{'username'}, $db_config{'password'},
) or die DBI->errstr();
my $sth = $dbh->prepare('SELECT todoid, todourl FROM todo')
  or die DBI->errstr();
$sth->execute() or die DBI->errstr();

my %todo;
while ( my $row = $sth->fetchrow_hashref() ) {
    $todo{ $row->{'todourl'} } = $row->{'todoid'};
}

Upvotes: 1

Related Questions