2014-02-17 28 views
0

我查詢表在數據庫與SQL這樣的:Perl的 - 從數據庫到數據結構

Select col1, col2 from table_name 

僅供參考,COL2將是一個整數值,並COL1將是一個元素的名稱。例如。

FOO, 3 
BAR, 10 

我希望有一個數據結構,其中的值可以像vars->{valueofcol1}解決應返回col2值。

所以

$vars->FOO 

將返回3

基本上我不知道如何將SQL結果返回到數據結構,我可以解決這個樣子。

+1

您是否檢查了用於訪問數據庫的模塊的手冊? –

+0

@mpapec不完全 – simbabque

+0

@leeduhem是的,但我不明白,因此我的問題 – user3318259

回答

1

您需要獲取伸手可及的距離並自行構建該hashref。

my $vars; # declare the variable for the hash ref outside the loop 
my $sth = $dbh->prepare(q{select col1, col2 from table_name}); 
$sth->execute; 
while (my $res = $sth->fetchrow_hashref) { # fetch row by row 
    $vars->{ $res->{col1} } = $res->{col2}; # build up data structure 
} 

print $vars->{FOO}; 

__END__ 
3 

您可能要read up on DBI,尤其是how to fetch stuff

+0

謝謝,我會測試這個代碼並回復你。 – user3318259