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 | [reply] [d/l] [select] |