I'm doing a lot of insert queries, and I think it would be best to write a subroutine for it. Something like insertRow($table, @stuff_to_insert). But how can I make the subroutine dynamic when it comes to the @stuff_to_insert, which can be anything from 1-5 arguments?
4 Answers
The best solution is probably using a ORM system such as DBIx::Class. They make handling SQL much easier.
If you choose to stay on raw DBI, I would advice you to use prepared statements like this:
my $query = sprintf 'INSERT INTO %s VALUES(%s)', dbh->quote_identifier($table), join ',', ('?') x $columns; my $sth = $dbh->prepare($query); for my $row (@rows) { $sth->execute(@{$row}); } This will be a speed and robustness benefit.
You can wrap it all up in a sub, but an ORM probably offers a better solution anyway.
6 Comments
Something like:
sub insertRow { my $table = shift; my $placeholders = join(',', map { "?"; } @_); $dbh->do("INSERT INTO $table VALUES ($placeholders)", undef, @_); } Edited: you need to add undef as a parameter. Leon Timmermans suggests not using prototypes
8 Comments
The parameter passing part of it is easy enough:
sub foo { my $table = shift; my @stuff_to_insert = @_; # Do stuff here } It doesn't matter whether you pass in one parameter, or five, or fifty, they'll all make it into @stuff_to_insert.
As for running the actual queries, take Leon's advice and use prepared statements. (ORMs can be handy, but, IMO, they're overrated and are serious overkill in simple cases.)