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

前端之家收集整理的这篇文章主要介绍了php – 如何使用PDO的持久连接?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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);
}
?>
原文链接:https://www.f2er.com/php/136182.html

猜你在找的PHP相关文章