大网数据广告活动
PHP 语言与运行手册

PDOException::getCode · Gets the SQLSTATE error code

· 52CE 我爱测

PDOException::getCode — Gets the SQLSTATE error code

PDOException::getCode

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

PDOException::getCode — Gets the SQLSTATE error code

Description

final public function PDOException::getCode(): int|string

Returns the exception code. This is the inherited Exception::getCode(), but unlike in most other exceptions, the code is usually a string.

Parameters

This function has no parameters.

Return Values

Returns the SQLSTATE as a five-character string (for example "42S02" or "HY000"), see PDO::errorCode().

If the connection fails in PDO::__construct(), returns the driver-specific error code as an int instead (for example 1045 for access denied in MySQL).

Caution

The code parameter of Exception::__construct() only accepts an int, so passing this value to it when rethrowing the error as a different exception throws a TypeError. Casting it to int loses information ("HY000" becomes 0). Pass the original exception as the previous parameter instead.

Examples

Example #1 PDOException::getCode() example

<?php
$pdo = new PDO('sqlite::memory:');

try {
    $pdo->query('SELECT * FROM missing_table');
} catch (PDOException $e) {
    var_dump($e->getCode());
}
?>

The above example will output:

string(5) "HY000"

Example #2 Rethrowing a PDOException

<?php
class DatabaseException extends RuntimeException {}

$pdo = new PDO('sqlite::memory:');

try {
    try {
        $pdo->query('SELECT * FROM missing_table');
    } catch (PDOException $e) {
        // Passing $e->getCode() as the code would throw a TypeError
        throw new DatabaseException('Query failed', previous: $e);
    }
} catch (DatabaseException $e) {
    echo $e->getMessage(), ': ', $e->getPrevious()->getCode(), "\n";
}
?>

The above example will output:

Query failed: HY000

See Also

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。