一.功能
1.可以访问其它数据库
2.具有事务功能
3.带有预处理语句功能(防止SQL注入攻击)
二.方法
1.造PDO对象
$dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123");
2.写SQL语句
$sql = "select * from nation";
$sql = "insert into nation values('n087','是是')";
3.执行SQL语句
$stm = $pdo->query($sql);
$arr = $pdo->exec($sql);
4.从PDOStatement对象里面读数据
$arr = $stm->fetchAll(PDO::FETCH_NUM);
var_dump($arr);
三.事务
1.流程
(1)beginTransaction 启动事务
(2)commit 提交事务
(3)rollback 回滚
2.方法
(1)造PDO对象
$dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123");
(2)将PDO的错误类型设置为异常模式
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
try
{
(3)开启事务
$pdo->beginTransaction();
$sql1 = "insert into nation values('n082','数据')";
$sql2 = "insert into nation values('n084','的库')";
$sql3 = "insert into nation values('n083','一帅哥')";
$pdo->exec($sql1);
$pdo->exec($sql2);
$pdo->exec($sql3);
(4)提交事务
$pdo->commit();
}
catch(Exception $e)
{
(5)回滚操作
$pdo->rollBack();
}
final
{
最终执行,无论有没有异常出现,该代码都会执行
}