【发布时间】: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 注入攻击,是一个很好的实践。