Skip to content

Instantly share code, notes, and snippets.

@typhonius
Created February 24, 2013 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save typhonius/5023159 to your computer and use it in GitHub Desktop.
Save typhonius/5023159 to your computer and use it in GitHub Desktop.
Wrapper function for inserting into an sqlite database using perl and prepared statements. The %values array is an associative array of column->value db_insert($table, %values);
sub db_connect() {
our $dbh = DBI->connect("dbi:SQLite:" . $path . '/' . $db,"","") or die "Unable to connect to database: $DBI::errstr";
return $dbh;
}
sub db_prepare($) {
my $dbh = db_connect();
my $query = shift;
my $handle = $dbh->prepare($query);
return $handle;
}
sub db_insert ( $ % ) {
my $table = shift;
my %inserts = %{$_[0]};
my $fields = join(', ', keys %inserts);
my @values = values %inserts;
my $q = '';
foreach (@values) {
$q .= "?, ";
}
$q = substr ($q, -length($q), -2);
my $query = "INSERT INTO $table ($fields) VALUES ($q)";
my $handle = db_prepare($query);
while (my ($index, $elem) = each @values) {
$handle->bind_param(($index + 1), $elem);
}
$handle->execute();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment