in reply to Re: Need an array as a function parameter
in thread Need an array as a function parameter

Field names are optional in an SQL insert statement provided you fill all fields. Of course it doesn't make for very readable code.

Omitting the field names might perhaps be a little faster as your database-engine does not have to map the values to the field names and can just sequentially fill all the fields. (I didn't benchmark it, I'm just guessing).

CountZero

"If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Replies are listed 'Best First'.
Re: Re: Re: Need an array as a function parameter
by optimist (Beadle) on Mar 27, 2004 at 23:15 UTC
    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