How to write a routine to insert a DBI with a different number of values?

I make a lot of insertion requests, and I think it would be better to write a subroutine for it. Something like that insertRow($table, @stuff_to_insert). But how can I make a dynamic routine when it comes to @stuff_to_insertwhich can be anything from 1-5 arguments?

+3
source share
4 answers

The best solution probably uses an ORM system such as DBIx :: Class . They greatly simplify SQL processing.

If you decide to stay on a raw DBI, I would advise you to use prepared statements as follows:

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

It will be speed and reliability.

sub, ORM, , .

+4

- :

sub insertRow
{
    my $table = shift;
    my $placeholders = join(',', map { "?"; } @_); 
    $dbh->do("INSERT INTO $table VALUES ($placeholders)", undef, @_);
}

: undef .       

+1

. insertRow, , ...

0

, , :

sub foo {
  my $table = shift;
  my @stuff_to_insert = @_;

  # Do stuff here
}

, , , @stuff_to_insert.

, . (ORM , , IMO, .)

0

Source: https://habr.com/ru/post/1703274/


All Articles