我正在尝试从 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 是否仍然知道它与哪个基因相关联?或者我是否需要为此创建某种哈希结构的哈希?
最佳答案
你调用了“错误”的函数
fetchrow_hashref
将返回 one 行作为 hashref,你应该将它的使用包装在一个循环中,当 fetchrow_hashref
返回 时结束它undef
。
您似乎在寻找 fetchall_hashref
,它将以散列形式为您提供所有返回的行,第一个参数指定要用作键的字段.
$hash_ref = $sth->fetchall_hashref ($key_field);
每一行都将作为内部 hashref 插入到 $hash_ref
中,使用 $key_field
作为键,您可以在 $hash_ref< 中找到该行
.
文档说了什么?
The fetchall_hashref method can be used to fetch all the data to be returned from a prepared and executed statement handle.
It returns a reference to a hash containing a key for each distinct value of the $key_field column that was fetched.
For each key the corresponding value is a reference to a hash containing all the selected columns and their values, as returned by fetchrow_hashref().
文档链接
关于mysql - 使用 fetchrow_hashref 存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8592053/