加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何使用PDO的持久连接?

发布时间:2020-12-13 13:04:05 所属栏目:PHP教程 来源:网络整理
导读:参见英文答案 Fully Understanding PDO ATTR_PERSISTENT3个 我有以下代码并在Firefox中刷新此网页5次,然后MySQL向我显示了5个连接.根据PDO手册, Persistent connections are not closed at the end of the script,but are cached and re-used when another s
参见英文答案 > Fully Understanding PDO ATTR_PERSISTENT3个
我有以下代码并在Firefox中刷新此网页5次,然后MySQL向我显示了5个连接.根据PDO手册,

Persistent connections are not closed
at the end of the script,but are
cached and re-used when another script
requests a connection using the same
credentials. The persistent connection
cache allows you to avoid the overhead
of establishing a new connection every
time a script needs to talk to a
database,resulting in a faster web
application.

我使用了相同的凭据,但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',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);
}
?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读