zoukankan      html  css  js  c++  java
  • 【代码总结】数据库抽象层PDO

    一、概述

    PDO就是一个"数据库访问抽象层",起作用是统一各种数据库的访问接口,能够轻松的在不同数据库之间进行切换。

    二、PDO的安装

    编辑php.ini文件

    添加

    extension=php_pdo.dll
    extension=php_pdo_mysql.dll

    重启APACHE

    三、以多种方式调用构造方法

    __construct(string $dsn[,string $username[,string $password[,array $driver _options]]])

    1.dsn:数据库源名,包括主机名商品号和数据库名称;
    2.username:连接数据库的用户名;
    3.password:连接数据库的密码;
    4.driver_options:连接数据库的其他选项;

    <?php
    //如果连接失败,使用异常处理模式进行捕获 
    try{
        $pdo = new PDO('mysql:host=localhost;charset=utf8;port=3306','root','root');
    
    }catch(PDOException $e){
        die('数据库连接失败');
    }
    ?>

    四、使用PDO执行SQL语句

    1、PDO:exec()方法

      用来处理非结果集 insert update delete create .....

    <?php
    //如果连接失败,使用异常处理模式进行捕获 
    try{
        $pdo = new PDO('mysql:host=localhost;dbname:test;charset=utf8;port=3306','root','root');
    
    }catch(PDOException $e){
        die('数据库连接失败');
    }
    try{
        //使用PDO中的方法执行语句
        $affect_rows = $pdo -> exec("insert into users(name,pass,sex) values('SQYY','123456','man')");
        echo $affect_rows;
    }catch(PDOException $e){
        echo "操作失败";
    }
    ?>

    2、PDO:query()方法

      用来处理有结果集的语句 select desc show

      返回来得失 PDOStatement类的对象,在通过这个类的方法获取结果

    <?php
    $pdo = new PDO('mysql:host=localhost;dbname:test;charset=utf8;port=3306','root','root');
    $query = "select name,pass,sex from user where id=1"
    
    try{
        //执行SELECT查询,并返回PDOStatement对象
        $pdostatement = $pdo -> query($query);
    }catch(PDOException $e){
        echo "操作失败";
    }
    ?>
  • 相关阅读:
    jmeter linux使用经验小结
    同步两台linux服务器时间同步方案
    jsp空页面导致的jvm heap溢出
    Struts2 interceptor使用经验小结
    转--Server “**” has shut down the connection prematurely一例分析
    Tomcat HTTP/1.1 Connector 参数整理
    严重: The web application [] registered the JDBC driver 错误
    JavaScript那些事
    jstl c标签 ”test does not support runtime expressions“
    SpringMvc文件资源防止被外链链接
  • 原文地址:https://www.cnblogs.com/sqyysec/p/6846033.html
Copyright © 2011-2022 走看看