我正在执行将数百条记录插入 MySQL 数据库的操作。
准确插入 176 条记录后,我收到此错误:
[PDOException] SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
关于如何解决它的任何想法?
这个过程是用PHP的。
最佳答案
我敢说问题在于 wait_timeout
。在我的共享主机上设置为 30 秒,在我的本地主机上设置为 28800。
我发现我可以为 session 更改它,因此您可以发出查询:SET session wait_timeout=28800
UPDATE OP 确定他还需要更改变量 interactive_timeout
。每个人都可能需要也可能不需要。
下面的代码显示了更改前后的设置,以验证是否已更改。
所以,在查询开始时设置 wait_timeout=28800(和 interactive_timeout = 28800),看看它是否完成。
记得插入您自己的数据库凭据来代替 DB_SERVER、DB_USER、DB_PASS、DB_NAME
更新另外,如果这确实有效,您希望通过将 wait_timeout 设置得更高来清楚自己在做什么。将它设置为 28800 是 8 小时,而且很多。
以下来自this site .它建议将 wait_timeout 设置为 300 - 我会尝试并报告我的结果(几周后)。
wait_timeout variable represents the amount of time that MySQL will wait before killing an idle connection. The default wait_timeout variable is 28800 seconds, which is 8 hours. That's a lot.
I've read in different forums/blogs that putting wait_timeout too low (e.g. 30, 60, 90) can result in MySQL has gone away error messages. So you'll have to decide for your configuration.
<?php
$db = new db();
$results = $db->query("SHOW VARIABLES LIKE '%timeout%'", TRUE);
echo "<pre>";
var_dump($results);
echo "</pre>";
$results = $db->query("SET session wait_timeout=28800", FALSE);
// UPDATE - this is also needed
$results = $db->query("SET session interactive_timeout=28800", FALSE);
$results = $db->query("SHOW VARIABLES LIKE '%timeout%'", TRUE);
echo "<pre>";
var_dump($results);
echo "</pre>";
class db {
public $mysqli;
public function __construct() {
$this->mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
exit();
}
}
public function __destruct() {
$this->disconnect();
unset($this->mysqli);
}
public function disconnect() {
$this->mysqli->close();
}
function query($q, $resultset) {
/* create a prepared statement */
if (!($stmt = $this->mysqli->prepare($q))) {
echo("Sql Error: " . $q . ' Sql error #: ' . $this->mysqli->errno . ' - ' . $this->mysqli->error);
return false;
}
/* execute query */
$stmt->execute();
if ($stmt->errno) {
echo("Sql Error: " . $q . ' Sql error #: ' . $stmt->errno . ' - ' . $stmt->error);
return false;
}
if ($resultset) {
$result = $stmt->get_result();
for ($set = array(); $row = $result->fetch_assoc();) {
$set[] = $row;
}
$stmt->close();
return $set;
}
}
}
关于php - 如何解决一般错误 : 2006 MySQL server has gone away,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250453/