問題描述
我正在使用 PDO 從 MySQL 服務器獲取數據.我注意到的是:如果 MySQL 服務器不可用,這段代碼需要真的(相對)很長時間才能返回異常:
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 的情況下,異常發生只需要 2 分鐘多一點(SQLSTATE[HY000] [2003] Can't connect to MySQL server on...)和 30 秒在 PostgreSQL (SQLSTATE[08006] [7] 超時已過期).
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.
有沒有辦法設置連接數據庫的超時時間?2 分鐘/30 秒對我來說似乎很長,讓 PDO 意識到那里什么都沒有.
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 設置連接超時的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!