代码之家  ›  专栏  ›  技术社区  ›  Jichao

如何使用PDO的持久连接?[副本]

  •  9
  • Jichao  · 技术社区  · 14 年前

    我有下面的代码,在Firefox中刷新了这个网页5次,然后MySQL显示了5个连接。根据PDO手册,

    永久连接未关闭 在剧本的结尾,但是 当另一个脚本 使用相同的 资格证书。持久连接 缓存允许您避免开销 建立新的联系 脚本需要与 数据库,使web更快 申请。

    我使用了相同的凭据,但是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();
    }
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   Big Zak    8 年前

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

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

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

    <?php 
    $dbh = DB::connect();
    
    foreach ($dbh->query('SELECT * from agent') as $row){ 
      print_r($row);
    }
    ?>
    
        2
  •  1
  •   Your Common Sense    8 年前

    据我所知,从持久连接来看,您可能不需要它:

    1. 您在本地主机上,因此连接速度非常快,并且不会从缓存连接中节省很多
    2. 由于Apache的基本原理,您有许多线程响应客户机请求,并且由于这些多线程,连接在一个线程中是持久的,而不是在所有线程上共享,因此您将看到mysql中的连接数增加,直到达到Apache的线程限制
    3. 持久连接可能会导致dbLock或tableLock类型的应用出现问题

    现在如果你仍然认为你真的需要的话,你可能想做更多关于持久连接的研究

        3
  •  1
  •   Community CDub    8 年前

    似乎您需要关闭游标并释放(赋值为空)到最后一个pdo语句对象来关闭连接。

    另外,了解持久连接的重要一点是它们是持久的,但不能保证您也不会:

    • 在以后的脚本执行中返回上一个连接处理程序
    • 也不要重用以前的连接,如果它仍然“忙”。忙可能意味着在脚本中,超时等。。。连接实例可能会持续不断。。。见 Fully Understanding PDO ATTR_PERSISTENT