We do it like this:
package DBH;
use strict;
use DBI ();
my $mysql_server = "You fill this in";
my $mysql_user = "You fill this in";
my $mysql_password = "You fill this in";
my $mysql_db = "You fill this in";
sub connect {
if (defined $DBH::conn) {
my $ret;
eval {
$ret = DBH->ping;
};
if (!$@ && $ret) {
return $DBH::conn;
}
}
$DBH::conn = DBI->connect(
"DBI:mysql:$mysql_db;$mysql_server",$mysql_user,$mysql_passwor
+d,
{
PrintError => 1,
RaiseError => 0,
}
) || die $DBI::errstr; #Assume application handles this
return $DBH::conn;
}
sub ping {
my $ret = 0;
if (time - $DBI::lastPing < 10) {
return 1;
}
eval {
local $SIG{__DIE__} = sub { return (0); };
local $SIG{__WARN__} = sub { return (0); };
# adapt the select statement to your database:
$ret = $DBH::conn->do('select 1');
$DBI::lastPing = time; #record time in seconds
};
$debug && print STDERR "DBH.pm: pinging DB handle: $ret\n";
return ($@) ? 0 : $ret;
}
1;
# now you can use this in your script:
#!/usr/bin/perl -w
use strict;
use DBH;
my $dbh = DBH->connect();
my $sth = $dbh->prepare("your query...");
"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.