我有以下代码并在 Firefox 中刷新该网页 5 次,然后 MySQL 显示了 5 个连接。根据 PDO 手册,
持久连接未关闭
在脚本的末尾,但是
缓存并在另一个脚本时重新使用
使用相同的方式请求连接
证书。持久连接
缓存可以让你避免开销
每隔一段时间就建立一个新的连接
脚本需要与
数据库,从而带来更快的网络
应用。
我使用了相同的凭据,但 MYSQL 连接数量不断增加。甚至试图与$db = null
无法关闭连接。
我的代码有什么问题吗?
<?php
try {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=lingtong', 'root', 'xxxxxx', array(PDO::ATTR_PERSISTENT => true));
foreach ($dbh->query('SELECT * from agent') as $row)
print_r($row);
$dbh = null;
} catch (PDOException $e) {
print "Error! : " . $e->getMessage() . "<br/>";
die();
}
这个问题很老了,但如果我贡献一下就可以了。我认为您需要实现一个单例类来处理数据库连接我将在下面编写一个示例类..
<?php
class DB{
//set the connection property to private to prevent direct access
private static $conn;
//now since we dont want to reinstiate the class anytime we need it, lets also set the constructor to private
private function __construct(){}
//now lets create our method for connecting to the database
public static function connect(){
//now lets check if a connection exists already in our $conn property, then we should return it instead of recreating a new connection
if(!empty(self::$conn)){
return self::$conn;
}//end if
//upon reaching here means the $conn property is empty so lets create a new connection
try {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=lingtong', 'root', 'xxxxxx', array(PDO::ATTR_PERSISTENT => true));
//lets now assign the database connection to our $conn property
self::$conn = $dbh;
//return the connection
return $dbh;
} catch (PDOException $e) {
print "Error! : " . $e->getMessage() . "<br/>";
die();
}
}//end method
}//end class
?>
我们的单例类只能建立一个连接并重用它,让我们看看如何使用我们的类
<?php
$dbh = DB::connect();
foreach ($dbh->query('SELECT * from agent') as $row){
print_r($row);
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)