是否可以在 DBI 允许 @bind_values 的地方使用命名占位符?例如,我想发表如下声明:
my $s = $DB->selectcol_arrayref ("SELECT a FROM b
WHERE c = ? OR d = ? OR e = ?;",
{},
$par1, $par2, $par1) or
die ($DB->errstr ());
不易出错。我正在使用 DBD::Pg 和 DBD::SQLite。
最佳答案
支持哪些类型的占位符(如果有)depends on the driver :
Placeholders and Bind Values
Some drivers support placeholders and bind values.
[...]
Some drivers also allow placeholders like :name and :N (e.g., :1, :2, and so on) in addition to ?, but their use is not portable.
但你很幸运,PostgreSQL driver支持命名或编号参数:
There are three types of placeholders that can be used in DBD::Pg. The first is the "question mark" type, in which each placeholder is represented by a single question mark character.
[...]
The method second type of placeholder is "dollar sign numbers".
[...]
The final placeholder type is "named parameters" in the format ":foo".
还有 SQLite driver也支持他们:
SQLite supports several placeholder expressions, including ? and :AAAA.
缺点是您最终会大量使用 bind_param
和命名参数,因此您将无法使用像 selectcol_arrayref
和 这样的便利工具$sth->execute(1,2,3)
(注意:如果有人知道如何在 execute
中使用命名占位符,我将不胜感激评论,我从来不知道该怎么做)。但是,您可以使用各种形式的数字占位符(例如 select c from t where x = $1
用于 PostgreSQL 或 select c from t where x = ?1
用于 SQLite ).
另请注意,PostgreSQL 对数组切片使用冒号,对某些运算符使用问号,因此有时标准的 ? 占位符和 :name 命名占位符可能会导致问题。 ? 我从未遇到过任何问题,但我从未使用过 geometric operators任何一个;我怀疑合理使用空格可以避免 ? 出现任何问题。如果您不使用 PostgreSQL 数组,那么您可能不必担心 array slices与你的 :name
命名占位符战斗。
执行摘要:您不能将命名占位符与 selectcol_arrayref
或与 @bind_params
一起使用的类似方法一起使用。但是,对于 SQLite 和 Postgresql,您可以使用带编号的占位符($1
、$2
、...对于 Postgresql 或 ?1
、 ?2
, ... 对于 SQLite)使用与 @bind_params
一起使用的方法,或者您可以使用命名占位符(:name
对于 PostgreSQL 和 SQLite)如果您乐于使用较长的 prepare
/bind_param
/execute
/fetch
方法序列,您将如果您在查询中使用 PostgreSQL 数组,则必须小心。
关于perl - 可以在 DBI 的 selectcol_arrayref & Co. 中使用命名占位符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627577/