PDO::prepare(): MySQL server has gone away in xxxx和SQLSTATE[HY000]: General error: 2006 MySQL server has gone away的错误,后来查了好多资料才发现是mysql有个最大连接时间,一般连接超时后会自动断开链接,但php进程中的连接池没有释放导致的。自己模拟了一下,在程序启动后重启mysql,或者强制杀掉连接进程后会必现。
后来在Connection.php数据库连接类中,将query和execute方法进行了适当的修改完美解决问题,所以希望官方能修复一下这个情况。
以下是我修改的步骤:
编辑 /ThinkPHP/library/think/db/Connection.php
加入新方法
/**
* 数据库重连配置
*/
private function reconnect()
{
$this->linkID = null;
$this->linkRead = null;
$this->linkWrite = null;
$this->links = [];
}将第361-363行的} catch (\PDOException $e) {
throw new PDOException($e, $this->config, $this->queryStr);
}修改为} catch (\Exception $e) {
if(false === stripos($e->getMessage(), 'server has gone away')) {
throw new PDOException($e, $this->config, $this->queryStr);
}
$this->reconnect();
return $this->query($sql, $bind, $master, $class);
}将第404-406行的} catch (\PDOException $e) {
throw new PDOException($e, $this->config, $this->queryStr);
}修改为} catch (\Exception $e) {
if(false === stripos($e->getMessage(), 'server has gone away')) {
throw new PDOException($e, $this->config, $this->queryStr);
}
$this->reconnect();
return $this->execute($sql, $bind);
}即可 