事务的典型运用就是通过把批量的改变“保存起来”然后立即执行。这样就会有彻底地提高更新效率的好处。换句话说,事务可以使你的脚本更快速同时可能更健壮(要实现这个优点你仍然需要正确的使用它们)。
不幸运的是,并不是每个数据库都支持事务,因此PDO需要在建立连接时运行在被认为是“自动提交”的模式下。自动提交模式意味着你执行的每个查询都有它自己隐含的事务处理,无论数据库支持事务还是因数据库不支持而不存在事务。如果你需要一个事务,你必须使用 PDO->beginTransaction() 方法创建一个。如果底层驱动不支持事务处理,一个PDOException就会被抛出(与你的异常处理设置无关,因为这总是一个严重的错误状态)。在一个事物中,你可以使用 PDO->commit() 或 PDO->rollBack() 结束它,这取决于事务中代码运行是否成功。
当脚本结束时或一个连接要关闭时,如果你还有一个未处理完的事务,PDO将会自动将其回滚。这是对于脚本意外终止的情况来说是一个安全的方案——如果你没有明确地提交事务,它将会假设发生了一些错误,为了你数据的安全,所以就执行回滚了。
二、PDOStatement
PDOStatement->bindColumn() — Bind a column to a PHP variable
PDOStatement->bindParam() — Binds a parameter to the specified variable name
PDOStatement->bindValue() — Binds a value to a parameter
PDOStatement->closeCursor() — Closes the cursor, enabling the statement to be executed again.
PDOStatement->columnCount() — Returns the number of columns in the result set
PDOStatement->errorCode() — Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement->errorInfo() — Fetch extended error information associated with the last operation on the statement handle
PDOStatement->execute() — Executes a prepared statement
PDOStatement->fetch() — Fetches the next row from a result set
PDOStatement->fetchAll() — Returns an array containing all of the result set rows
PDOStatement->fetchColumn() — Returns a single column from the next row of a result set
PDOStatement->fetchObject() — Fetches the next row and returns it as an object.
PDOStatement->getAttribute() — Retrieve a statement attribute
PDOStatement->getColumnMeta() — Returns metadata for a column in a result set
PDOStatement->nextRowset() — Advances to the next rowset in a multi-rowset statement handle
PDOStatement->rowCount() — Returns the number of rows affected by the last SQL statement
PDOStatement->setAttribute() — Set a statement attribute
PDOStatement->setFetchMode() — Set the default fetch mode for this statement
三、PDOException
PDO 提供了3中不同的错误处理策略。
1. PDO::ERRMODE_SILENT
这是默认使用的模式。PDO会在statement和database对象上设定简单的错误代号,你可以使用PDO->errorCode() 和 PDO->errorInfo() 方法检查错误;如果错误是在对statement对象进行调用时导致的,你就可以在那个对象上使用 PDOStatement->errorCode() 或 PDOStatement->errorInfo() 方法取得错误信息。而如果错误是在对database对象调用时导致的,你就应该在这个database对象上调用那两个方法。







