While this is standard SQL, or at least widely-enough supported that PostgreSQL also allows a single INSERT to add multiple rows, this builds an SQL query dynamically, which is generally a bad habit, since it can create a risk for SQL injection attacks if user-provided data is used to build the query.

Unless you have unusual requirements, a better way to achieve this is to prepare a statement that inserts a single row and then execute that statement once for each row, like the DBI manual(section "Outline Usage") suggests: (untested)

my @records = ( ['value1', 'value2'], ...) ; my $sth = $dbh->prepare("INSERT INTO $table (field1, field2) VALUES (? +,?)"); foreach my $valuesref (@records) { $sth->execute(@$valuesref) }

The other reason to do it this way is that the statement handle can be kept around and reused if records are to be inserted into the same table more than once. You can use $dbh->prepare_cached instead of $dbh->prepare, but see the caveats that are explained in the DBI manual.


In reply to Re: Proper Syntax for DBI multiple row insert by jcb
in thread Proper Syntax for DBI multiple row insert by Rodster001

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.