使用PDO设置连接超时

时间:2022-10-14 22:37:31

I'm using PDO to get data off SQL server. What I noticed is this: if the SQL server is unavailable, it takes really (relatively) long for this code to return an exception:

我正在使用PDO从SQL服务器上获取数据。我注意到的是:如果SQL服务器不可用,则此代码返回异常需要相当长的时间:

try {
  $handle = new PDO($db_type . ':host='.$db_host.';dbname='.$db_name,$db_user,$db_pass);
  // Tried using PDO::setAttribute and PDO::ATTR_TIMEOUT here
} catch(PDOException $e) {
  echo $e->getMessage;
}

In case of MySQL it takes just over 2 minutes for the exception to occur (SQLSTATE[HY000] [2003] Can't connect to MySQL server on...) and 30 seconds on PostgreSQL (SQLSTATE[08006] [7] timeout expired).

在MySQL的情况下,异常发生只需2分钟(SQLSTATE [HY000] [2003]无法连接到MySQL服务器......)和PostgreSQL上30秒(SQLSTATE [08006] [7]超时到期)。

I tried using PDO::setAttribute and PDO::ATTR_TIMEOUT but it's not working. Which I guess makes sense, since the problem occurs before this statement.

我尝试使用PDO :: setAttribute和PDO :: ATTR_TIMEOUT,但它不起作用。我认为这是有道理的,因为问题发生在这个陈述之前。

Is there a way to set a timeout for connecting to the DB? 2 minutes/30 seconds seems really long to me for PDO to realize there is nothing there.

有没有办法设置连接到DB的超时?对于PDO而言,2分30秒对我来说似乎真的很长时间才意识到那里什么也没有。

I think I saw this being done somewhere, but can't find it again for the life of me.

我想我看到这是在某个地方完成的,但在我的生活中再也找不到它。

2 个解决方案

#1


47  

$DBH = new PDO(
    "mysql:host=$host;dbname=$dbname", 
    $username, 
    $password,
    array(
        PDO::ATTR_TIMEOUT => "Specify your time here (seconds)",
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    )
);

#2


5  

I'm using the DBLIB driver for PDO - and that doesn't support the passing of options (throws a warning).

我正在使用DBLIB驱动程序进行PDO - 并且不支持传递选项(抛出警告)。

To get round this, you can edit the connection_timeout setting in the FreeTDS config file which is located at /etc/freetds/freetds.conf (on Ubuntu).

为了解决这个问题,您可以在FreeTDS配置文件中编辑connection_timeout设置,该文件位于/etc/freetds/freetds.conf(在Ubuntu上)。

#1


47  

$DBH = new PDO(
    "mysql:host=$host;dbname=$dbname", 
    $username, 
    $password,
    array(
        PDO::ATTR_TIMEOUT => "Specify your time here (seconds)",
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    )
);

#2


5  

I'm using the DBLIB driver for PDO - and that doesn't support the passing of options (throws a warning).

我正在使用DBLIB驱动程序进行PDO - 并且不支持传递选项(抛出警告)。

To get round this, you can edit the connection_timeout setting in the FreeTDS config file which is located at /etc/freetds/freetds.conf (on Ubuntu).

为了解决这个问题,您可以在FreeTDS配置文件中编辑connection_timeout设置,该文件位于/etc/freetds/freetds.conf(在Ubuntu上)。