my @keys = sort keys %cols; my $keystring = join ', ', @keys; my $valstring = join ', ', ('?') x scalar @keys; my $statement = qq{ INSERT INTO service_metrics ($keystring) VALUES ($valuestring) }; my @values = map { $cols{$_} } @keys; my $sth = $dbh->prepare($statement); if (! $sth) { die(sprintf('[FATAL] Could not prepare statement: %s\n\n + ERRSTR: %s\n', $db->errstr())); } $sth->execute(@values); if (! $sth) { die(sprintf('[FATAL] Could not execute statement: %s\n\n + ERRSTR: %s\n', $db->errstr())); } $sth->finish; $db->disconnect();
This is a bit less code and, by using placeholders, guards you against SQL injection.
You can learn more about placeholders in the DBI documentation.
The sorting of the keys eliminates the need to add supply an order manually.
If you have possibly undefined values, change the first line to
my @keys = grep { defined $cols{$_} } sort keys %cols;
In reply to Re: Receinving hash where expecting a string
by moritz
in thread Receinving hash where expecting a string
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |