【发布时间】:2023-03-04 22:46:01
【问题描述】:
如何在 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,理想情况下我想要一个不受数据库影响的通用解决方案。
【问题讨论】:
标签: sql perl dbi bind-variables