PDO:数据访问抽象层
一.作用:通过PDO能够访问其他数据库
二.用法
1.造PDO对象
$dsn = "mysql:dbname=test_123;host=localhost"; //数据源 = 驱动名:数据库名;
$pdo = new PDO($dsn,"root","123");
2.写sql语句
$sql = "select * from info";
$sql = "update info sey name='张三' where code='p005'";
3.执行SQL语句,返回PDOStatement对象
$stm = $pdo->query($sql);
$pdo->exec($sql);//适用于增删改
4.读数据
$arr = $stm->fetch(PDO::FETCH_ASSOC);
var_dump($arr);
$arr = $stm->fetchAll(PDO::FETCH_ASSOC);
var_dump($arr);
5.事务功能
$dsn = "mysql:dbname=test_123;host=localhost"; //数据源 = 驱动名:数据库名;
$pdo = new PDO($dsn,"root","123");
把PDO的错误模式设置为异常模式
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
捕获异常
try
{
//开启事务功能
$pdo->beginTransaction();
$sql1 = "insert into nation values('n008','哈哈')";
$sql2 = "insert into nation values('n009','GG')";
$sql3 = "insert into nation values('n010','MM')";
$pdo->exec($sql1);
$pdo->exec($sql2);
$pdo->exec($sql3);
//提交执行,提交事务
$pdo->commit();
}
catch(Exception $e)
{
//捕获异常并解决异常
//回滚
$pdo->rollBack();//相当于还原,还原到没有修改之前
}
二.预处理语句
$dsn = "mysql:dbname=test_123;host=localhost";
$pdo = new PDO($dsn,"root","123");
预处理语句方法一
$sql = "insert into nation values(?,?)";
将预处理语句发送到服务器等待执行,返回PDOStatement对象
$stm = $pdo->prepare($sql);
写法1:较麻烦
$stm->bindParam(1,$code);
$stm->bindParam(2,$nno);
$code = "n011";
$nno ="环境";
写法2:数组要跟问号相对应
$arr = array("n012","环境");
执行
$stm->execute($arr);
预处理语句方法二(最常用)
$dsn = "mysql:dbname=test_123;host=localhost";
$pdo = new PDO($dsn,"root","123");
$sql = "insert into nation values(:code,:nno)";
$stm = $pdo->prepare($sql);
$arr = array("code"=>"n013","nno"=>"嘿嘿");
$stm->execute($arr);