PDO::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDO::getAttribute 取回一个数据库连接的属性

说明

public PDO::getAttribute(int $attribute): mixed

此方法返回数据库连接属性的值。要检索 PDOStatement 属性,请参阅 PDOStatement::getAttribute()

注意有些数据库/驱动可能不支持所有的数据库连接属性。

参数

attribute

PDO::ATTR_* 常量之一。下列为应用到数据库连接中的通用属性:

  • PDO::ATTR_AUTOCOMMIT
  • PDO::ATTR_CASE
  • PDO::ATTR_CLIENT_VERSION
  • PDO::ATTR_CONNECTION_STATUS
  • PDO::ATTR_DRIVER_NAME
  • PDO::ATTR_ERRMODE
  • PDO::ATTR_ORACLE_NULLS
  • PDO::ATTR_PERSISTENT
  • PDO::ATTR_PREFETCH
  • PDO::ATTR_SERVER_INFO
  • PDO::ATTR_SERVER_VERSION
  • PDO::ATTR_TIMEOUT

一些驱动程序可能会使用额外的特定驱动程序属性。请注意,特定驱动程序的属性不能与其它驱动程序一起使用。

返回值

成功调用则返回请求的 PDO 属性值。不成功则返回 null

错误/异常

当底层驱动程序不支持请求的 attribute 时, PDO::getAttribute() 可能会抛出 PDOException

示例

示例 #1 取回数据库连接属性

<?php
$conn
= new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
"AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
"ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
"TIMEOUT"
);

foreach (
$attributes as $val) {
echo
"PDO::ATTR_$val: ";
echo
$conn->getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>

参见

添加备注

用户贡献的备注 2 notes

up
5
Phil Hilton
6 years ago
Better example that handles unsupported attributes gracefully:

<?php

$conn
= new PDO( 'odbc:sample', 'db2inst1', 'ibmdb2' );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$attributes = array(
"AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
"ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
"TIMEOUT"
);

foreach (
$attributes as $val ) {
echo
"PDO::ATTR_$val: ";
try {
echo
$conn->getAttribute( constant( "PDO::ATTR_$val" ) ) . "\n";
} catch (
PDOException $e ) {
echo
$e->getMessage() . "\n";
}
}

?>
up
0
Robert Parham
9 years ago
Oracle does not have the following attributes:

PDO::ATTR_CONNECTION_STATUS: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute
PDO::ATTR_PREFETCH: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute
PDO::ATTR_TIMEOUT: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute

The rest work fine.
To Top