Created
February 24, 2013 08:52
-
-
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);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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