如何使用PDO的永久连接? [英] How to use Persistent Connection of PDO?

查看:108
本文介绍了如何使用PDO的永久连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,并在Firefox中刷新了此网页5次,然后MySQL向我显示了5个连接.根据PDO手册,

I have the following code and freshed this webpage in Firefox for 5 times, then the MySQL showed me 5 connections. According to the PDO Manual,

持久连接未关闭 在脚本的末尾,但是 在另一个脚本时缓存并重新使用 使用相同的请求连接 证书.持久连接 缓存可以避免开销 建立一个新的连接 脚本需要与某人交谈的时间 数据库,从而加快了网络访问速度 应用程序.

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关闭连接也无法关闭连接. 我的代码有什么问题?

I have used the same credentials, but the number of MYSQL connection keep increasing. Even trying to close connection with $db = null could not close the connections. What's wrong of my code?

<?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();
}

推荐答案

这个问题很老,但是如果我做出贡献的话就可以了.我认为您需要实现一个用于处理数据库连接的单例类,我将在下面编写一个示例类.

This question is very old but it will be okay if I contribute. I think you need to implement a singleton class for handling database connections I will write a sample class below ..

<?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

?>

我们的单例类只能建立一个连接并重用它,让我们看看如何使用我们的类

Our singleton class can make only one connection and reuse it,let see how we can use our class

<?php 
$dbh = DB::connect();

foreach ($dbh->query('SELECT * from agent') as $row){ 
  print_r($row);
}
?>

这篇关于如何使用PDO的永久连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆