您可以使用MySQL 5.7+PDO::MYSQL_ATTR_INIT_COMMAND和PDO 执行此操作MAX_EXECUTION_TIME
工作示例
$pdo = new \PDO('mysql:the_rest_of_dns;', 'usrname', 'passwd', [
// Set time in miliseconds
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET SESSION MAX_EXECUTION_TIME=200;'
]);
$result = $pdo->query("SELECT * FROM answers");
/*
Catch mysql exception
*/
if(($error = $pdo->errorInfo())[0] !== "00000") {
/*
Query execution was interrupted, maximum statement execution time exceeded
exception exception handler
*/
if($error[1] === 3024) {
// Die with default error message
die($error[2]);
}
}
// If everything working fine, get the result
print_r($result->fetchAll());
一个重要的注意事项
超时仅适用于只读 SELECT 查询。
如果您不想在所有查询上设置超时,您可以使用以下命令输入提示:
SELECT /*+ MAX_EXECUTION_TIME(1000) */ status, count(*) FROM articles GROUP BY status ORDER BY status;
第二个例子取自这里。