mysql服务器不见了_解决“ MySQL服务器已消失”错误

小编典典

您可能倾向于通过在查询之前“ 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

}

}

}

}

}

2020-05-17

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值