2011-03-27 24 views
1

我遇到了Mysql和Perl的問題。Perl:在Perl-Hash中存儲來自Mysql-table的列

我正在編碼一個網絡爬蟲,我將TODO-List保存在一個Mysql表中。

現在,在腳本開始時,我想從Mysql將TODO-List加載到Perl哈希中,這樣我就不會重新抓取網址。

  • MySQL的具有以下 結構:

表 「待辦事項」 - 獨特ID 「todoid」 - 的 TODO的URL 「todourl」

  • 的Perl中的TODO哈希是這樣的:

my%todo =();

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

如何在我的todo散列中加載Mysql-table的所有Url?

回答

1

連接到使用DBI數據庫,準備查詢,執行查詢並獲取結果:

#!/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'}; 
} 
3

你可以使用DBI,像艾倫建議,但用更少的代碼:

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

正如你所看到的,我沒有使用DBI準備,執行,獲取和光潔度,因爲selectall_hashref方法做這一切爲了我們。

請參閱在線文檔:http://search.cpan.org/~timb/DBI-1.616/DBI.pm#selectall_hashref

相關問題