我的数据库有问题;我运行一个网站已经有半年了,到现在一直运行良好,因为访问时一直输出错误:
Database failed to connect: PDOException: SQLSTATE[08004] [1040] Too many connections in dbconfig.php:14
我对此进行了很长一段时间的研究,但找不到可能导致此问题的单一解决方案,因为半年后它如何突然出现很奇怪。
我的连接代码是这样的:
class Database {
private $host = "localhost";
private $db_name = "[...]";
private $username = "[...]";
private $password = "[...]";
public $conn;
public function dbConnection() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
exit('Database failed to connect: ' . $exception);
}
return $this->conn;
}
}
问题可能是什么?我也在其他网站上使用此代码,因此我希望这些网站不会很快出现相同的错误。
最佳答案
您似乎在这段代码中破坏了不必要的连接。如果已经建立连接,您应该重新使用该连接。此外,如果您有任何打开的语句或结果,这实际上不会关闭连接,而是会打开另一个连接。这可能是你的问题。同样,这实际上取决于您如何在实际脚本中使用此类。在同一脚本中重复调用此函数可能会导致您的问题。
因此,如果已经建立连接,则不要重用它。如果没有其他原因,实际建立与数据库的连接是一个相对较慢的过程。这通常称为单例模式。
class Database {
private $host = "localhost";
private $db_name = "[...]";
private $username = "[...]";
private $password = "[...]";
public $conn = null;
public function dbConnection() {
if ( $this->conn !== null ) {
// already have an open connection so lets reuse it
return $this->conn;
}
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
exit('Database failed to connect: ' . $exception);
}
return $this->conn;
}
}
关于php - PDO异常 : SQLSTATE[08004] [1040] Too many connections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343883/