Home >Database >Mysql Tutorial >How do I customize Connect Timeouts with PDO?

How do I customize Connect Timeouts with PDO?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 02:07:02427browse

How do I customize Connect Timeouts with PDO?

Customizing Connect Timeouts with PDO

When accessing data from a MySQL server using PDO, a long wait time can be encountered before an exception is thrown when the server is unavailable. To address this issue, a timeout for connecting to the database can be specified.

To set a connect timeout, use the PDO::ATTR_TIMEOUT attribute when creating the PDO instance. This attribute specifies the number of seconds to wait before timing out a connection attempt.

<code class="php">$DBH = new PDO(
    "mysql:host=$host;dbname=$dbname", 
    $username, 
    $password,
    array(
        PDO::ATTR_TIMEOUT => 5, // in seconds
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    )
);</code>

In this example, a timeout of 5 seconds is set. If the connection attempt takes longer than 5 seconds, a PDOException will be thrown.

It's important to note that this attribute affects only the initial connection attempt. Once the connection is established, subsequent queries will not be affected by this timeout.

The above is the detailed content of How do I customize Connect Timeouts with PDO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn