[英]Perl DBI - binding a list
How do I bind a variable to a SQL set for an IN query in Perl DBI? 如何在Perl DBI中为IN查询将变量绑定到SQL集?
Example: 例:
my @nature = ('TYPE1','TYPE2'); # This is normally populated from elsewhere
my $qh = $dbh->prepare(
"SELECT count(ref_no) FROM fm_fault WHERE nature IN ?"
) || die("Failed to prepare query: $DBI::errstr");
# Using the array here only takes the first entry in this example, using a array ref gives no result
# bind_param and named bind variables gives similar results
$qh->execute(@nature) || die("Failed to execute query: $DBI::errstr");
print $qh->fetchrow_array();
The result for the code as above results in only the count for TYPE1
, while the required output is the sum of the count for TYPE1
and TYPE2
. 上面代码的结果仅导致
TYPE1
的计数,而所需的输出是TYPE1
和TYPE2
的计数之和。 Replacing the bind entry with a reference to @nature
( \\@nature
), results in 0 results. 用对
@nature
( \\@nature
)的引用替换绑定条目,结果为0。
The main use-case for this is to allow a user to check multiple options using something like a checkbox group and it is to return all the results. 这样做的主要用例是允许用户使用复选框组之类的选项检查多个选项,并返回所有结果。 A work-around is to construct a string to insert into the query - it works, however it needs a whole lot of filtering to avoid SQL injection issues and it is ugly...
一种解决方法是构造一个要插入查询中的字符串-它可以工作,但是需要大量过滤才能避免SQL注入问题,而且这很丑陋。
In my case, the database is Oracle, ideally I want a generic solution that isn't affected by the database. 就我而言,数据库是Oracle,理想情况下,我想要不受数据库影响的通用解决方案。
There should be as many ?
应该有多少
?
placeholders as there is elements in @nature
, ie. 占位符,因为
@nature
有元素,即。 in (?,?,..)
my @nature = ('TYPE1','TYPE2');
my $pholders = join ",", ("?") x @nature;
my $qh = $dbh->prepare(
"SELECT count(ref_no) FROM fm_fault WHERE nature IN ($pholders)"
) or die("Failed to prepare query: $DBI::errstr");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.