Moritz von Schweinitz wrote:
>
> is there a nice way to qoute the contents of my %in, and insert them
> without always having to count question-marks, and watching out that the
> right hash-element maps to the right question-mark, which in turn maps
> to the correct column?
This function will accept a hash of any size and create the appropriate
number of placeholders and values and do the insert in the appropriate
order. You'd call it like this:
my $rv = insert_hash( $dbh, $tablename, %in );
sub insert_hash {
my $dbh = shift;
my $tablename = shift;
my %in = @_;
my @colnames = keys %in;
my @colvalues = @in{ @colnames };
my $paramStr = join ',', ('?') x @colnames;
my $colStr = "@colnames";
$colStr =~ s/ /,/g;
my $sql = "INSERT INTO $tablename ($colStr) VALUES ($paramStr)";
$dbh->do( $sql, undef, @colvalues );
}
You'd be wise to check %in before calling this to make sure that all of
its keys are valid column names in the table and all of its value are
things you actually want in the database.
--
Jeff