vancetech has asked for the wisdom of the Perl Monks concerning the following question:
This could indicate faulty hardware on my network. The code I am using error traps ALL mysql functions that I can, however, when this error occurs, my script hangs while ->execute()'ing a statement. I cannot recover it by error trapping or even using an eval{ alarm() } and ALRM signal handler.060727 15:44:16 Aborted connection 109 to db: 'test_0_8' user: 'test' +host: `test.com' (Got an error reading communication packets)
#!/usr/bin/perl use strict; use DBI; use DBD::mysql; my $dbh = db_connect(); $|++; my $i = 0; while( 1 ) { if ($i < 1000) { # Do queries if( my $res = db_query("SELECT * FROM monitor_list WHERE id = +$i") ) { while( my $row = $res->fetchrow_hashref() ) { print "Failed to insert this record\n" unless db_query +("INSERT INTO test VALUES ( $i, " . rand(6000) . ", " . rand(7000) . +" )"); print "+"; } print "$i "; $i+=3; } } else { # Clear work if( db_query( "DELETE FROM test" ) ) { $i = 0; print "\n"; } else { print "Failed to clear table\n"; } } } sub db_query() { my $sql = $_[0]; my $sth; eval { local $SIG{ALRM} = sub {die "timeout"}; alarm( 4 ); my($s, $m, $h) = (localtime)[0,1,2]; print "$h:$m:$s "; if( ref $dbh ) { print "R"; if( $dbh->ping() ) { print "P"; if( $sth = $dbh->prepare($sql) or handle() ) { print "S"; if( $sth->execute() or handle() ) { print "E\n"; } } } else { $dbh = db_connect(); } } }; if( $@ ) { print "Timed out\n"; return 0; } return $sth; } sub handle() { print "Got error: " . $dbh->err . " = " . $dbh->errstr . "\n"; return 0; } sub db_connect() { my ($database, $hostname, $username, $port, $dsn, $user, $password +, $driver, $dbh, $sth , $sql); $driver = "mysql"; while( !$dbh ) { $dsn = "DBI:$driver:database=$database;host=$hostname;mysql_co +nnect_timeout=3"; if( $dbh = DBI->connect($dsn, $username, $password, { PrintErr +or => 0, RaiseError => 0 }) ) { $dbh->{mysql_auto_reconnect} = 1; print "DB Connected\n"; return( $dbh ); } else { warn( $DBI::errstr ); sleep(2); } } return( undef ); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: trapping mysql errors
by Khen1950fx (Canon) on Jul 28, 2006 at 04:17 UTC | |
|
Re: trapping mysql errors
by jdtoronto (Prior) on Jul 28, 2006 at 04:32 UTC | |
by vancetech (Beadle) on Jul 28, 2006 at 16:43 UTC | |
by vancetech (Beadle) on Jul 28, 2006 at 17:33 UTC |