PHP中PDO的错误处理_PHP
面向对象的方式
先看看如果连接错误等的处理,PHP中PDO的错误处理,使用面向对象的方式来处理:
复制代码 代码如下:
try {
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$db = null;
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "
";
die();
}
?>
这里利用我们PHP 5面向对象的异常处理特征,如果里面有异常的话就初始化调用PDOException来初始化一个异常类。
PDOException异常类的属性结构:
复制代码 代码如下:
class PDOException extends Exception
{
public $errorInfo = null; // 错误信息,可以调用 PDO::errorInfo() 或 PDOStatement::errorInfo()来访问
protected $message; // 异常信息,可以试用 Exception::getMessage() 来访问
protected $code; // SQL状态错误代码,可以使用 Exception::getCode() 来访问
}
?>
这个异常处理类是集成PHP 5内置的异常处理类,我们简单的看一下PHP 5内置的异常处理类结构:
复制代码 代码如下:
class Exception
{
// 属性
protected $message = 'Unknown exception'; // 异常信息
protected $code = 0; // 用户自定义异常代码
protected $file; // 发生异常的文件名
protected $line; // 发生异常的代码行号
// 方法
final function getMessage(); // 返回异常信息
final function getCode(); // 返回异常代码
final function getFile(); // 返回发生异常的文件名
final function getLine(); // 返回发生异常的代码行号
final function getTrace(); // backtrace() 数组
final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息
}
?>
相应的,在代码中可以合适的调用 getFile() 和 getLine() 来进行错误定位,更方便的进行调试。
使用面向过程的方法
先看代码:
复制代码 代码如下:
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$rs = $db->query("SELECT aa,bb,cc FROM foo");
if ($db->errorCode() != '00000'){
print_r($db->errorInfo());
exit;
}
$arr = $rs->fetchAll();
print_r($arr);
$db = null;
?>
PDO和PDOStatement对象有errorCode() 和 errorInfo() 方法,如果没有任何错误, errorCode() 返回的是: 00000 ,否则就会返回一些错误代码。errorInfo() 返回的一个数组,包括PHP定义的错误代码和MySQL的错误代码和错误信息,数组结构如下:
Array
(
[0] => 42S22
[1] => 1054
[2] => Unknown column 'aaa' in 'field list'
)
每次执行查询以后,errorCode() 的结果都是最新的,所以我们可以很容易自己控制错误信息显示。
在使用PDO进行那个PHP和数据库开发过程中,如果再碰到错误咋办?按照上面的方式处理吧。
11.3.4 PDO的错误处理
PDO提供了两个获得程序中的错误信息的方法,一个是errorCode()方法;另一个是errorInfo()方法。
1.errorCode()方法
errorCode()方法用于获取在操作数据库句柄时所发生的错误代码,这些错误代码被称为SQLSTATE代码,该方法的语法格式如下:
01 string errorCode ( void ) errorCode()方法的返回值为一个SQLSTATE,SQLSTATE是由5个数字和字母组成的代码。下面是使用errorCode()方法的示例:
【程序11-17】光盘\code\11\pdo\errorCode.php
复制代码 代码如下:
$dsn = 'mysql:dbname=shop;host=localhost';
$user_name = 'root';
$user_psw = 'root';
$pdo = new PDO($dsn, $user_name, $user_psw);
$pdo->exec("update mytable set age=28 where id=1 ");//表mytable不存在
echo "errorCode为: ".$pdo->errorCode();
?>
上述代码输出的错误代码如图11-13所示。
2.errorInfo()方法
errorInfo()方法用于获得操作数据库句柄时所发生的错误信息,该方法的语法格式如下:
01 array errorInfo ( void ) errorInfo()方法的返回值为一个数组,该数组里面包含了相关的错误信息,使用errorInfo()方法的示例代码如下:
【程序11-18】光盘\code\11\pdo\errorInfo.php
复制代码 代码如下:
$dsn = 'mysql:dbname=shop;host=localhost';
$user_name = 'root';
$user_psw = 'root';
$pdo = new PDO($dsn, $user_name, $user_psw);
$pdo->exec("update mytable set age=28 where id=1 ");//表mytable不存在
echo "errorInfo为: ";
print_r($pdo->errorInfo());
?>
上面代码输出的错误信息如图11-14所示。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Use middleware to improve error handling in Go functions: Introducing the concept of middleware, which can intercept function calls and execute specific logic. Create error handling middleware that wraps error handling logic in a custom function. Use middleware to wrap handler functions so that error handling logic is performed before the function is called. Returns the appropriate error code based on the error type, улучшениеобработкиошибоквфункциях Goспомощьюпромежуточногопрограммногообеспечения.Оно позволяетнамсосредоточитьсянаобработкеошибо

In C++, exception handling handles errors gracefully through try-catch blocks. Common exception types include runtime errors, logic errors, and out-of-bounds errors. Take file opening error handling as an example. When the program fails to open a file, it will throw an exception and print the error message and return the error code through the catch block, thereby handling the error without terminating the program. Exception handling provides advantages such as centralization of error handling, error propagation, and code robustness.

The best error handling tools and libraries in PHP include: Built-in methods: set_error_handler() and error_get_last() Third-party toolkits: Whoops (debugging and error formatting) Third-party services: Sentry (error reporting and monitoring) Third-party libraries: PHP-error-handler (custom error logging and stack traces) and Monolog (error logging handler)

In Go functions, asynchronous error handling uses error channels to asynchronously pass errors from goroutines. The specific steps are as follows: Create an error channel. Start a goroutine to perform operations and send errors asynchronously. Use a select statement to receive errors from the channel. Handle errors asynchronously, such as printing or logging error messages. This approach improves the performance and scalability of concurrent code because error handling does not block the calling thread and execution can be canceled.

In Go function unit testing, there are two main strategies for error handling: 1. Represent the error as a specific value of the error type, which is used to assert the expected value; 2. Use channels to pass errors to the test function, which is suitable for testing concurrent code. In a practical case, the error value strategy is used to ensure that the function returns 0 for negative input.

Error handling and logging in C++ class design include: Exception handling: catching and handling exceptions, using custom exception classes to provide specific error information. Error code: Use an integer or enumeration to represent the error condition and return it in the return value. Assertion: Verify pre- and post-conditions, and throw an exception if they are not met. C++ library logging: basic logging using std::cerr and std::clog. External logging libraries: Integrate third-party libraries for advanced features such as level filtering and log file rotation. Custom log class: Create your own log class, abstract the underlying mechanism, and provide a common interface to record different levels of information.

In Golang, error wrappers allow you to create new errors by appending contextual information to the original error. This can be used to unify the types of errors thrown by different libraries or components, simplifying debugging and error handling. The steps are as follows: Use the errors.Wrap function to wrap the original errors into new errors. The new error contains contextual information from the original error. Use fmt.Printf to output wrapped errors, providing more context and actionability. When handling different types of errors, use the errors.Wrap function to unify the error types.

There are two ways to handle errors gracefully in Go: The defer statement is used to execute code before the function returns, usually to release resources or log errors. The recover statement is used to catch panics in functions and allow the program to handle errors in a more graceful manner instead of crashing.
