2013 php network_error ai_generated true

PDOException:SQLSTATE[HY000] [2013] 查询期间与 MySQL 服务器失去连接,位于 /var/www/app/src/Database/QueryBuilder.php 第 78 行

PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server during query in /var/www/app/src/Database/QueryBuilder.php on line 78

ID: php/pdo-mysql-query-timeout

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
1证据数
2024-06-05首次发现

版本兼容性

版本状态引入弃用备注
7.4 active
8.0 active
8.1 active
8.2 active
8.3 active

根因分析

长时间运行的查询超过了 MySQL 的 wait_timeout 或 net_read_timeout,或者 MySQL 服务器在查询过程中重启或崩溃,导致连接断开。

English

A long-running query exceeds MySQL's wait_timeout or net_read_timeout, or the MySQL server restarted or crashed mid-query, causing the connection to drop.

generic

官方文档

https://dev.mysql.com/doc/refman/8.0/en/error-messages-client.html#error_cr_server_gone_error

解决方案

  1. Increase MySQL's wait_timeout and net_read_timeout in my.cnf: [mysqld] wait_timeout = 600 net_read_timeout = 600. Restart MySQL: sudo systemctl restart mysql
  2. Optimize the slow query by adding indexes or splitting it into smaller chunks. Example: $chunks = array_chunk($largeArray, 1000); foreach ($chunks as $chunk) { // execute query with chunk }
  3. Implement a retry mechanism with exponential backoff in PHP: for ($attempt = 1; $attempt <= 3; $attempt++) { try { $stmt->execute(); break; } catch (PDOException $e) { if ($e->getCode() !== '2013') throw $e; usleep(pow(2, $attempt) * 100000); } }

无效尝试

常见但无效的做法:

  1. 85% 失败

    PDO timeout affects connection attempts, not query execution. The MySQL server's own timeout settings are the limiting factor.

  2. 90% 失败

    Persistent connections can help with connection overhead but do not prevent timeouts during queries.