package My::parser::db; use strict; use warnings; use DBI; sub new { my $class = shift; my $config = shift; my $rest = shift; return \$class if($rest); my $self = {}; bless ($self, $class); $self->{'config'} = $config; return $self; } sub init { my $self = shift; return $self->{'config'}->get_dbh(); } sub connect { my $self = shift; my $config = $self->{'config'}; my $usr = $config->get_as_single_val('config','dbusr'); my $pwd = $config->get_as_single_val('config','dbpwd'); my $host = $config->get_as_single_val('config','dbhost'); my $db = $config->get_as_single_val('config','db'); my $dbh; if($usr && $pwd && $host && $db) { my $logstr = 'Connecting to DB...'; my $i = 0; while(1) { last if($dbh = DBI->connect("DBI:mysql:database=$db;host=$host",$usr,$pwd, { PrintError => 1, mysql_auto_reconnect=>0, AutoCommit => 1 })); sleep($i); $i++; unless ($i % 10) { $self->{'config'}->{'logger'}->log($logstr.'timed out, retry #'.$i); } } $config->set_dbh($dbh); $self->{'config'}->{'logger'}->log($logstr.'done'); return $config->get_dbh(); } else { $self->{'config'}->{'logger'}->log("Unable to connect to db, not enough parameters"); return 0; } } 1;