orlybg orlybg - 5 months ago 16
Perl Question

Perl DBI execute with an array instead of list of scalars

I build a query depending on certain conditions - such as type of operation, or the presence of a certain value - by adding fields to a

INSERT
statement. But then I have to branch for different DBI
execute
s with different lists of parameters, like this:

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);}


I would prefer to do something like this:

{$sth->execute($anArrayWithDifferentParams);}


Is this possible? Or is there another way to do something similar?

Answer

To more directly answer the question, the way to execute a query with an array instead of a list of scalars is simply to pass it an array. $sth->execute(@params) will work just fine.

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);
Comments