Perl DBI使用数组而不是标量列表执行

orl*_*ybg 1 perl dbi

我通过向INSERT语句添加字段,根据某些条件(例如操作类型或存在某个值)构建查询.但后来我必须为不同的DBI分支execute不同的参数列表,如下所示:

if ($x) {$extraFields .= ' , X'; $extraValues= ',? '}
if ($y) {$extraFields .= ' , Y, Z'; $extraValues= ',?, ? '}

my $theBasicQuery = "INSERT INTO sometable (A, B, $extraFields) VALUES (?, ? $extraValues)";

$sth = $dbh->prepare($theBasicQuery) or error

# but I dont want to have to do this if for execute
if ($x) {$sth->execute(1,2,99);}
if ($y) {$sth->execute(1,2,88, 77);}
Run Code Online (Sandbox Code Playgroud)

我宁愿做这样的事情:

{$sth->execute($anArrayWithDifferentParams);}
Run Code Online (Sandbox Code Playgroud)

这可能吗?或者还有其他方法可以做类似的事情吗?

Dav*_*man 6

为了更直接地回答这个问题,使用数组而不是标量列表执行查询的方法就是将数组传递给它. $sth->execute(@params)会工作得很好.

if ($x) {$extraFields .= ' , X'; $extraValues = ',? '; @params = (99); }
if ($y) {$extraFields .= ' , Y, Z'; $extraValues = ',?, ? '; @params = (88, 77); }

my $theBasicQuery = "INSERT INTO sometable (A, B, $extraFields) VALUES (?, ? $extraValues)";

$sth = $dbh->prepare($theBasicQuery) or error

$sth->execute(1,2, @params);
Run Code Online (Sandbox Code Playgroud)