使用fetchrow_hashref存储数据

时间:2011-12-21 15:15:42

标签: mysql perl hash

我试图从MySQL数据库中获取信息,然后我将在perl中操作:

use strict;
use DBI;

my $dbh_m= DBI->connect("dbi:mysql:Populationdb","root","LisaUni") 
or die("Error: $DBI::errstr");

my $Genotype = 'Genotype'.1;
#The idea here is eventually I will ask the database how many Genotypes there are, and then loop it round to complete the following for each Genotype:

my $sql =qq(SELECT TransNo, gene.Gene FROM gene JOIN genotypegene ON gene.Gene =       genotypegene.Gene WHERE Genotype like '$Genotype');
my $sth = $dbh_m-> prepare($sql);
$sth->execute;

my %hash;

my $transvalues = $sth->fetchrow_hashref;
my %hash= %$transvalues;

$sth ->finish();
$dbh_m->disconnect();       

my $key;
my $value;

while (($key, $value) = each(%hash)){
 print $key.", ".$value\n; }

此代码不会产生任何错误,但%hash只存储从数据库中取出的最后一行(我想到了从this website开始编写它的方法)。如果我输入:

while(my $transvalues = $sth->fetchrow_hashref){
print "Gene: $transvalues->{Gene}\n";
print "Trans: $transvalues->{TransNo}\n";
}

然后它会打印掉所有行,但是一旦我关闭了与数据库的连接,我就需要所有这些信息。

我也有一个相关的问题:在我的MySQL数据库中,该行由例如'Gene1'(Gene)'4'(TransNo)组成。一旦我从上面的数据库中取出数据,TransNo是否仍然知道它与哪个Gene相关联?或者我是否需要为此创建某种哈希结构的哈希?

1 个答案:

答案 0 :(得分:6)

您正在调用“错误”功能

fetchrow_hashref会将一个行作为hashref返回,你应该将它包含在循环中,当fetchrow_hashref返回 undef时结束它/ em>的

您好像正在寻找 fetchall_hashref ,它会将所有返回的行作为哈希,第一个参数指定要用作键的字段。

$hash_ref = $sth->fetchall_hashref ($key_field);

每行将作为内部hashref插入$hash_ref,使用$key_field作为关键字,您可以在$hash_ref中找到该行。

文件说什么?

  

fetchall_hashref方法可用于获取从准备好并执行的语句句柄返回的所有数据。

     

它返回对包含获取的$ key_field列的每个不同值的键的哈希的引用。

     

对于每个键,相应的值是对包含所有选定列及其值的哈希的引用,由fetchrow_hashref()返回。


文档链接