我试图从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; }
Run Code Online (Sandbox Code Playgroud)
此代码不会产生任何错误,但%hash只存储从数据库中获取的最后一行(我从这个网站以这种方式编写它的想法).如果我输入:
while(my $transvalues = $sth->fetchrow_hashref){
print "Gene: $transvalues->{Gene}\n";
print "Trans: $transvalues->{TransNo}\n";
}
Run Code Online (Sandbox Code Playgroud)
然后它会打印掉所有行,但是一旦我关闭了与数据库的连接,我就需要所有这些信息.
我还有一个相关的问题:在我的MySQL数据库中,该行包含例如'Gene1'(Gene)'4'(TransNo).一旦我从上面的数据库中取出数据,TransNo是否仍然知道它与哪个Gene相关联?或者我是否需要为此创建某种哈希结构的哈希?
fetchrow_hashref会返回一个行作为一个hashref,你应该把它包装是一个循环内使用,当它结束fetchrow_hashref的回报undef.
看起来你正在寻找fetchall_hashref,它会将所有返回的行作为哈希,第一个参数指定要用作键的字段.
$hash_ref = $sth->fetchall_hashref ($key_field);
Run Code Online (Sandbox Code Playgroud)
每行将$hash_ref作为内部hashref 插入,使用$key_field您可以在其中找到行的键$hash_ref.
fetchall_hashref方法可用于获取从准备和执行的语句句柄返回的所有数据.
它返回对包含获取的$ key_field列的每个不同值的键的哈希的引用.
对于每个键,相应的值是对包含所有选定列及其值的哈希的引用,由fetchrow_hashref()返回.