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 "操作失败";
    }
    ?>
  • 相关阅读:
    【rust】Rust 的构建系统和包管理工具Cargo认识并初步使用(2)
    【rust】rust安装,运行第一个Rust 程序 (1)
    linux 双网卡桥接,实现网卡流量镜像与转发
    【原创】使用golang访问windows telnet服务器
    使用centos 7安装conpot
    用Redis作Mysql数据库缓存
    python解析处理snmp回显----snmp
    snmp自定义OID与文件下载----服务器端配置
    golang map输出排序
    计算机组成原理---第1章 计算机系统概述
  • 原文地址:https://www.cnblogs.com/sqyysec/p/6846033.html
Copyright © 2011-2022 走看看