perl DBI和占位符

smi*_*ith 11 perl dbi

我有这个问题 select * from table where ID in (1,2,3,5...)

如何使用占位符与DBI构建此查询?

例如 :

my @list = (1, 2, 3, 4, 5);
my $sql = "select * from table where ID in (?)";

$sth->prepare($sql);
$sth->execute();
Run Code Online (Sandbox Code Playgroud)

我应该发送什么参数来执行?它是一个由,其他东西分隔的列表或字符串吗?

cch*_*son 28

这应该根据数组中的项目数动态构建您的查询

my @list =(1,2,3,4,5);
my $sql ="select * from table where ID in (@{[join',', ('?') x @list]})";
Run Code Online (Sandbox Code Playgroud)


Mig*_*Prz 11

以这种方式是不可能的.您需要为数组中的每个项指定占位符:

my @list = (1,2,3,4,5);
my $sql = "select * from table where ID in (?,?,?,?,?)";

$sth->prepare($sql);
$sth->execute(@list);
Run Code Online (Sandbox Code Playgroud)

如果您的@list大小不是固定的,则需要$sql使用适当数量的占位符构建.


Ala*_*avi 6

引用DBI文件:

此外,占位符只能表示单个标量值.例如,以下语句对于多个值不会按预期工作:

     SELECT name, age FROM people WHERE name IN (?)    # wrong
     SELECT name, age FROM people WHERE name IN (?,?)  # two names
Run Code Online (Sandbox Code Playgroud)

重写为:

my $sql = 'select * from table where ID in ( ?, ?, ?, ?, ? )';
$sth->prepare($sql);
$sth->execute(@list);
Run Code Online (Sandbox Code Playgroud)


Tim*_*idt 5

如果您使用 DBI 通过 DBD::Pg 驱动程序访问 PostgreSQL 数据库,则可以使用:

my @list = (1, 2, 3, 4, 5);
my $sql = "select * from table where ID = ANY(?::INT[]);";

$sth->prepare ($sql);
$sth->execute (\@list);
Run Code Online (Sandbox Code Playgroud)