【问题标题】:Using fetchrow_hashref to store data使用 fetchrow_hashref 存储数据
【发布时间】:2012-01-25 09:31:18
【问题描述】:

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

【问题讨论】:

  • 关于 Perl 中的 SQL 语句的一个旁注,您可以将变量从 $sql 变量中取出并作为执行语句的一部分包含在内。试试这个:my $sql =qq(SELECT ... WHERE Genotype like ?); my $sth = $dbh_m-> prepare($sql); $sth->execute($Genotype); 这将防止 SQL 注入攻击,是一个很好的实践。

标签: mysql perl hash


【解决方案1】:

你调用了“错误”的函数

fetchrow_hashref 将返回 one 行作为 hashref,你应该将它的使用包装在一个循环中,当fetchrow_hashref 返回时结束它undef。 p>

您似乎正在寻找 fetchall_hashref,它会将所有返回的行作为散列提供给您,其中第一个参数指定用作键的字段。

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

每一行将作为内部哈希引用插入$hash_ref,使用$key_field 作为关键字,您可以在其中找到$hash_ref 中的行。

文档是怎么说的?

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

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

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


文档链接

【讨论】:

  • 谢谢 - 我现在改成:my $transvalues = $sth->fetchall_hashref('Gene'); print $transvalues->{Gene1}->{TransNo} 我将如何循环它以打印所有基因?
  • 通过.. 创建一个遍历 hashref 的循环,你几乎回答了这个问题,这个问题。示例codepad.org/31SEnbYs(另外,请接受答案以将问题标记为已解决)
猜你喜欢
  • 2014-11-08
  • 2016-07-21
  • 2012-01-26
  • 2012-12-02
  • 2017-04-28
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多