您可能倾向于通过在查询之前“ ping”
MySQL服务器来解决此问题。这是一个坏主意。有关为什么的更多信息,请查看以下SO帖子:在每次查询之前都应该ping
mysql服务器吗?
解决此问题的最佳方法是将查询包装在
try/catch块中并捕获任何数据库异常,以便您可以适当地处理它们。这在长时间运行和/或守护程序类型的脚本中尤其重要。因此,这是一个非常基本的示例,使用“连接管理器”来控制对数据库连接的访问:
class DbPool { private $connections = array(); function addConnection($id, $dsn) { $this->connections[$id] = array( 'dsn' => $dsn, 'conn' => null ); } function getConnection($id) { if (!isset($this->connections[$id])) { throw new Exception('Invalid DB connection requested'); } elseif (isset($this->connections[$id]['conn'])) { return $this->connections[$id]['conn']; } else { try { // for mysql you need to supply user/pass as well $conn = new PDO($dsn); // Tell PDO to throw an exception on error // (like "MySQL server has gone away") $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $this->connections[$id]['conn'] = $conn; return $conn; } catch (PDOException $e) { return false; } } } function close($id) { if (!isset($this->connections[$id])) { throw new Exception('Invalid DB connection requested'); } $this->connections[$id]['conn'] = null; }}class Crawler { private $dbPool; function __construct(DbPool $dbPool) { $this->dbPool = $dbPool; } function crawl() { // craw and store data in $crawledData variable $this->save($crawledData); } function saveData($crawledData) { if (!$conn = $this->dbPool->getConnection('write_conn') { // doh! couldn't retrieve DB connection ... handle it } else { try { // perform query on the $conn database connection } catch (Exception $e) { $msg = $e->getMessage(); if (strstr($msg, 'MySQL server has gone away') { $this->dbPool->close('write_conn'); $this->saveData($val); } else { // some other error occurred } } } }}


