php pdo函数库用法举例

发布时间:2020-11-26编辑:脚本学堂
php pdo函数库的用法,包括 pdo、pdostatement 和 pdoexception的用法示例,pdo数据库连接与事务的例子,pdostatement及pdoexception错误处理的方法等。

php pdo包含三个预定义的类,分别是 pdo、pdostatement 和 pdoexception。

一、pdo函数库
pdo->begintransaction() — 标明回滚起始点
pdo->commit() — 标明回滚结束点,并执行sql
pdo->rollback() — 执行回滚
pdo->__construct() — 建立一个pdo链接数据库的实例
pdo->errorcode() — 获取错误码
pdo->errorinfo() — 获取错误的信息
pdo->exec() — 处理一条sql语句,并返回所影响的条目数
pdo->getattribute() — 获取一个"数据库连接对象"的属性
pdo->getavailabledrivers() — 获取有效的pdo驱动器名称
pdo->lastinsertid() — 获取写入的最后一条数据的主键值
pdo->prepare() — 生成一个"查询对象"
pdo->query() — 处理一条sql语句,并返回一个"pdostatement
pdo->quote() — 为某个sql中的字符串添加引号
pdo->setattribute() — 为一个"数据库连接对象"设定属性

1、pdo数据库连接

复制代码 代码示例:
$dsn = 'mysql:dbname=ent;host=127.0.0.1′;
$user = 'root';
$password = '123456′;
try {
$dbh = new pdo($dsn, $user, $password, array(pdo::attr_persistent => true));
$dbh->query('set names utf8;');
foreach ($dbh->query('select * from tpm_juese') as $row) {
print_r($row);
}
} catch (pdoexception $e) {
echo 'connection failed: ' . $e->getmessage();
}
 

许多web应用会因为使用了向数据库的持久连接而得到优化。持久连接不会在脚本结束时关闭,
相反它会被缓存起来并在另一个脚本通过同样的标识请求一个连接时得以重新利用。
持久连接的缓存可以使你避免在脚本每次需要与数据库对话时都要部署一个新的连接的资源消耗,让你的web应用更加快速。
上面实例中的array(pdo::attr_persistent => true)就是把连接类型设置为持久连接。

2、pdo事务
pdo->begintransaction(),pdo->commit(),pdo->rollback()这三个方法是在支持回滚功能时一起使用的。pdo->begintransaction()方法标明起始点,pdo->commit()方法标明回滚结束点,并执行sql,pdo->rollback()执行回滚。
 

复制代码 代码示例:
try {
$dbh = new pdo('mysql:host=localhost;dbname=test', 'root', ");
$dbh->query('set names utf8;');
$dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception);
$dbh->begintransaction();
$dbh->exec("insert into `test`.`table` (`name` ,`age`)values ('mick', 22);");
$dbh->exec("insert into `test`.`table` (`name` ,`age`)values ('lily', 29);");
$dbh->exec("insert into `test`.`table` (`name` ,`age`)values ('susan', 21);");
$dbh->commit();
} catch (exception $e) {
$dbh->rollback();
echo "failed: " . $e->getmessage();
}
?>
 

现在已通过pdo建立了连接,在部署查询之前你必须搞明白pdo是怎样管理事务的。如果你以前从未遇到过事务处理,(现在简单介绍一下:)它们提供了4个主要的特性:原子性,一致性,独立性和持久性(atomicity, consistency, isolation and durability,acid)通俗一点讲,一个事务中所有的工作在提交时,即使它是分阶段执行的,也要保证安全地应用于数据库,不被其他的连接干扰。事务工作也可以在请求发生错误时轻松地自动取消。

事务的典型运用就是通过把批量的改变"保存起来"然后立即执行。这样就会有彻底地提高更新效率的好处。换句话说,事务可以使你的脚本更快速同时可能更健壮(要实现这个优点你仍然需要正确的使用它们)。

并不是每个数据库都支持事务,因此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对象上调用那两个方法。

2、pdo::errmode_warning
作为设置错误代号的附加,pdo将会发出一个传统的e_warning信息。这种设置在除错和调试时是很有用的,如果你只是想看看发生了什么问题而不想中断程序的流程的话。

3、pdo::errmode_exception
作为设置错误代号的附件,pdo会抛出一个pdoexception异常并设置它的属性来反映错误代号和错误信息。这中设置在除错时也是很有用的,因为他会有效的"放大(blow up)"脚本中的出错点,非常快速的指向一个你代码中可能出错区域。(记住:如果异常导致脚本中断,事务处理回自动回滚。)

异常模式也是非常有用的,因为可以使用比以前那种使用传统的php风格的错误处理结构更清晰的结构处理错误,比使用安静模式使用更少的代码及嵌套,也能够更加明确地检查每个数据库访问的返回值。