脚本宝典收集整理的这篇文章主要介绍了php – 如何使用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); } ?>
以上是脚本宝典为你收集整理的php – 如何使用PDO的持久连接?全部内容,希望文章能够帮你解决php – 如何使用PDO的持久连接?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。