PDO :: getAttribute(PDO :: ATTR_CONNECTION_STATUS)的可能结果是什么? [英] What are the possible results of PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS)

查看:418
本文介绍了PDO :: getAttribute(PDO :: ATTR_CONNECTION_STATUS)的可能结果是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找这几乎所有的一天..和似乎找不到任何地方返回的值。有人可以告诉我:

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. 什么值 PDO :: getAttribute(PDO :: ATTR_CONNECTION_STATUS); return?

  2. 是否可以依赖其结果来确定连接是否仍然活着?(最终,我可以使用什么来检查连接是否仍然活着?)

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


推荐答案

事实证明, mysqli :: ping()函数可以在PDO中实现如下:

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(); 返回包含结果的数组false,在当前情况下它不会返回任何东西,cuz连接死了,PDO应该抛出一个异常在我们。这就是我们所期望的。 catch块将返回false,并且不会停止我们脚本的执行。使用的查询

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;

SELECT 1+1;

将始终返回2,并且它是好的依赖,因为它是在DB端计算的事实。没有连接,没有结果!它不是一个overkill,因为它是非常简单的查询和大多数数据库(在正常的共享主机)是在localhost它不会超过 0.0000s 这不是很多的性能问题。尚未测试它的交易,但应该做的诡计。

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.

这篇关于PDO :: getAttribute(PDO :: ATTR_CONNECTION_STATUS)的可能结果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆