php 使用 PDO 设置连接超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21403082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting a connect timeout with PDO
提问by gkres
I'm using PDO to get data off a MySQL server. What I noticed is this: if the MySQL server is unavailable, it takes really(relatively) long for this code to return an exception:
我正在使用 PDO 从 MySQL 服务器获取数据。后来我发现是这样的:如果MySQL服务器不可用,它需要真正的(相对)长此代码返回一个例外:
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] timeout expired) )。
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.
有没有办法设置连接到数据库的超时时间?2 分钟/30 秒对我来说似乎很长,让 PDO 意识到那里什么都没有。
I think I saw this being done somewhere, but can't find it again for the life of me.
我想我在某个地方看到过这种情况,但在我的生活中再也找不到了。
回答by Shinto Joseph
$DBH = new PDO(
"mysql:host=$host;dbname=$dbname",
$username,
$password,
array(
PDO::ATTR_TIMEOUT => 5, // in seconds
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
回答by gbuckingham89
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_timeoutsetting in the FreeTDS config file which is located at /etc/freetds/freetds.conf(on Ubuntu).
为了解决这个问题,您可以编辑connection_timeout位于/etc/freetds/freetds.conf(在 Ubuntu 上)的 FreeTDS 配置文件中的设置。

