【发布时间】:2016-01-27 08:01:54
【问题描述】:
我的代码中出现了一个奇怪的错误,这似乎只在我尝试使用占位符和引号标识符进行查询时发生。我编写了以下子例程来检查条目是否存在,如果存在则返回密钥,如果不存在则返回 null:
sub check_exists {
my $table=$_[0]; #table
my $col=$_[1];
my $check=$_[2]; #query for item
#check if value exists
my $sql=sprintf(qq(SELECT COUNT(1) FROM %s WHERE ?=?),
$dbh->quote_identifier($table));
my $sth = $dbh->prepare($sql);
$sth->execute($col,$check);
my $result=$sth->fetch()->[0];
$sth->finish();
#if value exists find the row and return the primary key
if ($result){
my $sql = sprintf(qq(SELECT %s FROM %s WHERE ?=?),
$dbh->quote_identifier=$col,
$dbh->quote_identifier=$table);
my $sth2=$dbh->prepare($sql);
$sth2->execute($col,$check);
return ($sth2->fetch()->[0]); #return key
}
else {
return 0; #else value does not exist and return null
}
}
我什至尝试过:
my $result=$dbh->selectrow_array(sprintf(qq(SELECT COUNT(1) FROM %s WHERE ?=?),$dbh->quote_identifier($table)),undef, $col, $check);
不幸的是,它总是返回零。如果我不使用占位符,它似乎可以工作。
my $test=$dbh->selectrow_array(qq(SELECT COUNT(1) FROM ORF1 WHERE idORF1=?),undef,$orf1_crc32)
谁能解释我做错了什么?
【问题讨论】:
-
如上所述,您不能对列名或表名使用占位符。值只能使用占位符。
-
我认为您可以将 quote_identifier 用于表和列。
-
我知道我做错了什么,令人尴尬的是,我没有意识到
WHERE正在寻找一个列,我认为它是一个值。一旦我也在专栏上使用了quote_identifier(),它现在就可以工作了。谢谢大家!