Many DBD drivers support BLOB columns natively. Most drivers/databases require you to use bind variables (which are usualy safer and often more efficient than composing quoted strings of sql code). Using bind params is not that difficult, assuming you are using mysql, and have a table named foo 'create table foo (data BLOB)', the following contrived example code should work for you:
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect('dbi:mysql:krb','mortis','');
die $DBI::errstr unless $dbh;
if (@ARGV) {
my $img_file = 'test.jpg';
my $img_data = getFile($img_file);
my $sql = 'INSERT INTO foo (data) VALUES (?)';
unless ($dbh->do($sql,undef,$img_data)) {
die "Error executing sql: '$sql' : $DBI::errstr : ",$dbh->errstr,"
+\n";
}
print "DATA INSERTED\n";
}
my $resultSet = $dbh->selectall_arrayref('SELECT * FROM foo');
my $imgData = $resultSet->[0]->[0];
writeFile('test2.jpg',$imgData);
$dbh->disconnect;
sub getFile {
my($file) = @_;
my $fh;
unless (open $fh, "<", $file) {
die "Error opening $file : $!\n";
}
my $data;
{ local $/ = undef; $data = <$fh>; }
close $fh;
return $data;
}
sub writeFile {
my($file,$data) = @_;
my $fh;
unless (open $fh, ">", $file) {
die "Error opening $file : $!\n";
}
print $fh $data;
close $fh;
}
Iirc, DBD::Oracle supports blobs natively in the same manner (you might have to pass statement handle attributes to identify the column's type though). DBD::Pg also supports blob columns, though you need to have blob access inside of a transaction, and you used to have to call some Postgresql specific DBD api to use them. Newer versions may be better.
hth,
Kyle |