2

I would like to insert a single row through perl dbi, but this row has A LOT of columns. My query would be smt like this :

$sth->prepare("insert into bigtable (col1, col2, ..., col25) values (?, ?, ..., ?)");
$sth->execute($val1, $val2, ..., $val25);

But I want it cleaner. If I have an array, @myArray, containing these 25 variables, is there a way to do smt like this :

$sth->prepare("insert into bigtable (col1, col2, ..., col25) values (?, ?, ..., ?)");
$sth->execute(@myArray);

?

3
  • 2
    Did you try the second block of code? That should work. search.cpan.org/~timb/DBI-1.618/DBI.pm#execute Commented Mar 23, 2012 at 13:40
  • I did, but got an error about hash references. I'll try it again tonight, and update the post. Thanks. Commented Mar 23, 2012 at 14:20
  • It's fixed, this was indeed correct, had an error somewhere else .. somehow. thanks anyway ! Commented Mar 26, 2012 at 6:55

1 Answer 1

4

You can do:

my $placeholders = join ", ", ("?") x @array;
$sth->prepare("insert into bigtable (col...) values ($placeholders)");
$sth->execute(@array);
Sign up to request clarification or add additional context in comments.

2 Comments

And even my $cols = join(', ', map { "col$_" } 1 .. @array); if column names are exactly like in the question.
@mcsi Yep, and you don't even need curly braces: map "col$_", 1..@array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.