mysql - 使用 fetchrow_hashref 存储数据

标签 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 是否仍然知道它与哪个基因相关联?或者我是否需要为此创建某种哈希结构的哈希?

最佳答案

你调用了“错误”的函数

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/

相关文章:

python mysql错误<class '_mysql_exceptions.ProgrammingError'>

mysql - 在 MySQL 中使用 BLOB 时,是否可以设置允许的图像文件的最大大小?

regex - Perl 中用于替换的匹配数字

perl - Parse::FixedLength 修剪问题

perl - 数据库驱动器 :SQLite disconnect

c - 对哈希函数的 undefined reference

javascript - 即使字段为空也会执行mysql查询

mysql - 每个用户每年的 SUM 总计、按用户分组、每年的动态列

algorithm - 概率文件验证——算法还是库?

java - 如何使 "MessageDigest SHA-1 and Signature NONEwithRSA"等同于 "Signature SHA1withRSA "