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手册,
我使用了相同的凭据,但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); } ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |