DBIでのエラー発生でスクリプトを終了させずに処理を行う方法のメモ
次の例では、エラー発生でスクリプトが中断(終了)する。
#!/isr/bin/perl
use warnings;
use strict;
use utf8;
use DBI;
my $str_dsn = 'DBI:SQLite:dbname=/var/www/perl-dbi-test/data/test.db';
my $dbh = DBI->connect($str_dsn, '', '', {PrintError => 0, AutoCommit => 1}) or die("connect error (".DBI::errstr.")\n");
my $str_query = "insert into test_tbl values(null,?,?)";
$sth = $dbh->prepare($str_query) or die("prepare error (".DBI::errstr.")\n");
$sth->execute($str_data1, $str_data2) or die("execute error (".DBI::errstr.")\n");
$dbh->disconnect();
次のようにすれば、エラー発生時のdieをキャッチして、スクリプトを終了させない
#!/isr/bin/perl
use warnings;
use strict;
use utf8;
use DBI;
my $str_dsn = 'DBI:SQLite:dbname=/var/www/perl-dbi-test/data/test.db';
my $dbh = undef;
eval{
$dbh = DBI->connect($str_dsn, '', '', {PrintError => 0, AutoCommit => 1}) or die(DBI::errstr);
my $str_query = "insert into test_tbl values(null,?,?)";
$sth = $dbh->prepare($str_query) or die(DBI::errstr);
$sth->execute($str_data1, $str_data2) or die(DBI::errstr);
$dbh->disconnect();
}
if($@){
if(defined($dbh)){ $dbh->disconnect(); }
print "error(".$@.")\n";
}
DBIモジュールでのエラーはDBI::errstrに返されているので、これをdieの引数として渡す(if文の$@に渡される)か、もしくはif文内でDBI::errstrを呼び出すか、どちらでも良いと思う。
■ 参考リンク
・[Perl]evalの中で起こったエラーを検出する