Sql Perl—从数据库到数据结构

Sql Perl—从数据库到数据结构,sql,perl,dbi,perl-data-structures,Sql,Perl,Dbi,Perl Data Structures,我正在使用SQL查询数据库中的表,如下所示: Select col1, col2 from table_name 作为参考,col2将是一个整数值,col1将是一个元素的名称。例如 FOO, 3 BAR, 10 我想要一个数据结构,其中的值可以像vars->{valueOfcl1}那样寻址,应该返回col2的值 所以 将返回3 基本上,我不知道如何将SQL结果返回到我可以这样处理的数据结构中。您需要获取reach行并自己构建hashref my $vars; # declare the va

我正在使用SQL查询数据库中的表,如下所示:

Select col1, col2 from table_name
作为参考,col2将是一个整数值,col1将是一个元素的名称。例如

FOO, 3
BAR, 10
我想要一个数据结构,其中的值可以像
vars->{valueOfcl1}
那样寻址,应该返回
col2
的值

所以

将返回3


基本上,我不知道如何将SQL结果返回到我可以这样处理的数据结构中。

您需要获取reach行并自己构建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

您可能会想,尤其是。

您是否查阅了用于访问数据库的模块手册?@leeduhem是的,但我不明白,因此我question@mpapec这个数据结构看起来太深了,不符合我的想法。实际上,你必须做
$vars->{FOO}
,因为它是一个散列键。您不能执行
$vars->FOO
,因为
$vars
未被加入到类中,因此Perl无法从该类包调用子
FOO
。谢谢,我将测试此代码并返回给您。
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