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

- **ID:** `php/pdo-mysql-query-timeout`
- **领域:** php
- **类别:** network_error
- **错误码:** `2013`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.4 | active | — | — |
| 8.0 | active | — | — |
| 8.1 | active | — | — |
| 8.2 | active | — | — |
| 8.3 | active | — | — |

## 解决方案

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); } }
   ```

## 无效尝试

- **** — PDO timeout affects connection attempts, not query execution. The MySQL server's own timeout settings are the limiting factor. (85% 失败率)
- **** — Persistent connections can help with connection overhead but do not prevent timeouts during queries. (90% 失败率)
