如何将变量绑定到 Perl DBI 中 IN 查询的 SQL 集?
例子:
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();
上述代码的结果仅产生 的计数TYPE1
,而所需的输出是 和 的计数之TYPE1
和TYPE2
。将绑定条目替换为对@nature
( \@nature
) 的引用,结果为 0。
主要用例是允许用户使用复选框组之类的东西检查多个选项,并返回所有结果。一种解决方法是构造一个要插入到查询中的字符串 - 它可以工作,但是它需要大量过滤以避免 SQL 注入问题,而且它很丑......
就我而言,数据库是 Oracle,理想情况下,我想要一个不受数据库影响的通用解决方案。