pdo mysql timeout,使用PDO设置连接超时

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;

}

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

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.

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

)

);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值