The trouble with omitting column names in the insert statement is that, if your database structure ever changes, your code will magically start breaking, but it won't necessarily be obvious why. So it's less robust, as well as being less readable.

Perhaps dhoss might want to consider (sorry, this is untested):

sub insert { my $self = shift; my ($table, $columns, $values) = @_; my $sql = sprintf("insert into %s (%s) values (%s)", $table, join(',', @$columns), join(',' map { '?' } @$values); my $sth = $dbh->prepare($sql) or die $dbh->errstr; $sth->execute(@$values) or die $sth->errstr; }

You'd call it as

$obj->insert($tablename, \@column_names, \@values)
It will give you a reasonably useful error message (at least in MySQL) if the table structure stops matching the column names in your code. Plus, using ? placeholders in the prepared statement, and passing the values to execute will handle all the quoting issues for you.

Note I wouldn't use this, or any of the alternatives so far, any place I expected to get called repeatedly (e.g., in a loop). IIRC preparing a statement, either explicitly or via do is often a more expensive operation than executing it, so you'd want to pull the prepare out of your loop somehow, or else memoize the prepared statement.

HTH,
optimist


In reply to Re: Re: Re: Need an array as a function parameter by optimist
in thread Need an array as a function parameter by stonecolddevin

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.