PDO
在线手册:中文 英文
PHP手册

Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

Example #1 Create a PDO instance and set the error mode

<?php
$dsn 
'mysql:dbname=testdb;host=127.0.0.1';
$user 'dbuser';
$password 'dbpass';

try {
    
$dbh = new PDO($dsn$user$password);
    
$dbh->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
} catch (
PDOException $e) {
    echo 
'Connection failed: ' $e->getMessage();
}

?>


PDO
在线手册:中文 英文
PHP手册
PHP手册 - N: Errors and error handling

用户评论:

john dot navratil at sbcglobal dot net (07-Jun-2008 11:38)

SQLSTATE code strings cannot be counted on, yet.  Attempting to insert a row with a duplicate key provides the 23000 code (constraint violation) when using mysql, but HY000 when using Oracle.  The PDO docs say this is the responsibility of the driver to convert.  In the meantime, the app will have to do it.

radical (22-Apr-2008 08:45)

For your convenience, here's an example of how to set the error handling:

<?php

  $dbh
= new PDO( /* your connection string */ );
 
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
 
// . . .
?>