我正在尝试从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’(基因) '4'(TransNo)组成。一旦我像上面那样从数据库中取出这些数据,TransNo还会知道它与哪个基因相关吗?或者我需要为此创建某种散列结构的散列?
发布于 2011-12-21 23:26:47
您调用的是“错误的”函数
fetchrow_hashref将返回一个行作为hashref,您应该将它的使用包装在一个循环中,当fetchrow_hashref返回undef时结束它。
看起来您正在寻找的fetchall_hashref,将把所有返回的行作为散列提供给您,其中第一个参数指定了要用作键的字段。
$hash_ref = $sth->fetchall_hashref ($key_field);每一行都将作为内部hashref插入到$hash_ref中,并使用$key_field作为可以在$hash_ref中查找该行的键。
文档是怎么说的?
fetchall_hashref方法可用于从已准备并已执行的语句句柄获取要返回的所有数据。
它返回对散列的引用,该散列包含所获取的$key_field列的每个不同值的键。
对于每个键,相应的值是对包含所有选定列及其值的散列的引用,由fetchrow_hashref()返回。
文档链接
https://stackoverflow.com/questions/8592053
复制相似问题