使用PDO设置连接超时 [英] Setting a connect timeout with PDO
问题描述
我正在使用PDO从MySQL服务器获取数据.我注意到的是:如果MySQL服务器不可用,则此代码返回异常的时间为 really (相对)很长:
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:
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;
}
对于MySQL,发生异常(SQLSTATE [HY000] [2003]无法连接到...上的MySQL服务器)仅需2分钟以上,而在PostgreSQL(SQLSTATE [08006] [7]上则需要30秒]超时已过期).
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).
我尝试使用PDO :: setAttribute和PDO :: ATTR_TIMEOUT,但是它不起作用.我猜这是有道理的,因为问题出在此声明之前.
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来说,2分钟30秒对我来说真的很长,要意识到那里什么也没有.
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.
我认为我在某处看到了这一点,但是在我的一生中再也找不到了.
I think I saw this being done somewhere, but can't find it again for the life of me.
推荐答案
$DBH = new PDO(
"mysql:host=$host;dbname=$dbname",
$username,
$password,
array(
PDO::ATTR_TIMEOUT => 5, // in seconds
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
这篇关于使用PDO设置连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!