Database Reference
In-Depth Information
begin
dsn = "DBI:Mysql:host=localhost;database=cookbook"
dbh = DBI . connect ( dsn , "baduser" , "badpass" )
puts "Connected"
rescue DBI : :DatabaseError => e
puts "Cannot connect to server"
puts "Error code: #{ e . err } "
puts "Error message: #{ e . errstr } "
puts "Error SQLSTATE: #{ e . state } "
exit ( 1 )
end
PHP
The new PDO() constructor raises an exception if it fails, but other PDO methods by
default indicate success or failure by their return value. To cause all PDO methods to
raise exceptions for errors, use the database handle resulting from a successful connec‐
tion attempt to set the error-handling mode. This enables uniform handling of all PDO
errors without checking the result of every call. The following example shows how to
set the error mode if the connection attempt succeeds and how to handle exceptions if
it fails:
try
{
$dsn = "mysql:host=localhost;dbname=cookbook" ;
$dbh = new PDO ( $dsn , "baduser" , "badpass" );
$dbh -> setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION );
print ( "Connected \n " );
}
catch ( PDOException $e )
{
print ( "Cannot connect to server \n " );
print ( "Error code: " . $e -> getCode () . " \n " );
print ( "Error message: " . $e -> getMessage () . " \n " );
}
When PDO raises an exception, the resulting PDOException object provides error in‐
formation. The getCode() method returns the SQLSTATE value. The getMessage()
method returns a string containing the SQLSTATE value, MySQL error number, and
error message.
Database and statement handles also provide information when an error occurs. For
either type of handle, errorCode() returns the SQLSTATE value and errorInfo()
returns a three-element array containing the SQLSTATE value and a driver-specific
error code and message. For MySQL, the latter two values are the error number and
message string. The following example demonstrates how to get information from the
exception object and the database handle:
try
{
Search WWH ::




Custom Search