What are the possible results of PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS)

半城伤御伤魂 提交于 2019-12-10 13:19:22

问题


I have been looking in to this almost all day.. and can't seem to find the values returned anywhere. Can somebody tell me:

  1. What values do PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS); return?
  2. Is it possible to rely on its result to determinate if the connection is still alive?(And eventually, what could I use to check if the connection is still alive?)

回答1:


Finally! it turns out that the mysqli::ping() function could be implemented within PDO as follows:

class PDOExtended extends PDO {
    public function __construct($dsn, $user, $pass, $options = array())
    {
        $this->link = parent::__construct($dsn, $user, $pass, $options);
        $this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
    }

    // some methods

    public function isConnected()
    {
        try {
            return (bool) $this->link->query('SELECT 1+1');
        } catch (PDOException $e) {
            return false;
        }
    }

    //some other methods
}

REASON:
PDO::query(); returns array containing the results or false, In the current case it won't return nothing, cuz the connection is dead and PDO should throw an exception at us. And that is what we are expecting. The catch block will return false and and will not stop the execution of our script. The query used

SELECT 1+1;

will return 2 always and it is good to rely on due to the fact that it is calculated on the DB side. No connection, no result! It is not an overkill because it is very simple query and most of the databases (on normal shared host) are on localhost it will not take more than 0.0000s which is not much of a performance issue. Have not tested it with transactions yet, but should do the trick still.



来源:https://stackoverflow.com/questions/15642734/what-are-the-possible-results-of-pdogetattributepdoattr-connection-status

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!