Skip to content

Instantly share code, notes, and snippets.

@kazeburo
Created April 6, 2011 10:25
Show Gist options
  • Select an option

  • Save kazeburo/905445 to your computer and use it in GitHub Desktop.

Select an option

Save kazeburo/905445 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use DBI;
use Data::Dumper;
sub serialize {
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Indent = 0;
":".Data::Dumper::Dumper(shift);
}
my $callback = sub {
my ($obj,$query,$attr,@binds) = @_;
$obj->{private_bind_value} = @binds ? serialize(\@binds) : "";
return;
};
my %callbacks;
$callbacks{$_} = $callback for qw/do selectrow_array selectrow_arrayref
selectrow_hashref selectall_arrayref
selectall_hashref selectcol_arrayref/;
my $dbh = DBI->connect("dbi:SQLite:dbname=/tmp/hoge.db", '', '', {
RaiseError => 0,
PrintError => 0,
ShowErrorStatement => 0,
HandleError => sub {
my ( $errstr, $obj ) = @_;
if ( ref($obj) =~ m/::(?:db|st)$/ ) {
die sprintf "%s | %s %s\n", $errstr, $obj->{Statement}, $obj->{private_bind_value};
}
die sprintf "%s\n", $errstr;
},
Callbacks => {
%callbacks,
connected => sub {
my $connect = shift;
$connect->do(<<EOF);
CREATE TABLE IF NOT EXISTS entries (
id VARCHAR(255) NOT NULL PRIMARY KEY,
nick VARCHAR(255) NOT NULL,
body TEXT,
ctime DATETIME NOT NULL
)
EOF
$connect->do(<<EOF);
CREATE INDEX IF NOT EXISTS index_ctime ON entries ( ctime )
EOF
return;
},
ChildCallbacks => {
execute => sub {
my $obj = shift;
$obj->{private_bind_value} = @_ ? serialize(\@_) : "";
return;
},
}
},
});
eval {
$dbh->do("hoge");
};
warn $@;
eval {
my $sth = $dbh->prepare('select * from entries limit ?,10');
$sth->execute('a');
};
warn $@;
eval {
$dbh->selectrow_arrayref('select * from entries limit ?,?',{},'a',100);
};
warn $@;
__END__
#mysql
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'hoge' at line 1 | hoge
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '10' at line 1 | select * from entries limit ?,10 :['a']
DBD::mysql::db selectrow_arrayref failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '100' at line 1 | select * from entries limit ?,? :['a',100]
#sqlite
DBD::SQLite::db do failed: near "hoge": syntax error | hoge
DBD::SQLite::st execute failed: datatype mismatch | select * from entries limit ?,10 :['a']
DBD::SQLite::db selectrow_arrayref failed: datatype mismatch | select * from entries limit ?,? :['a',100]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment