• 单例模式连接数据库


      类的单例模式只需要执行一次数据库连接,可以防止数据库的多次连接给服务器造成负担

      PHP示例代码

      

    <?php
    require_once 'config.php';
    class DB
    {
        protected $host;
        protected $user;
        protected $password;
        protected $dbname;
        protected $db;
        protected static $c;
        //构造函数 初始化 私有 禁止外部调用
        private function __construct($host = DB_DBNAME, $user = DB_USER, $password = DB_PASSWORD, $dbname = DB_NAME)
        {
            $this->host = $host;
            $this->user = $user;
            $this->password = $password;
            $this->dbname = $dbname;
            //    判断数据库是否连接
            if ($this->db) {
                $this->db = conn();
            }
        }
        // 连接数据库
        function conn()
        {
            $conn = new mysqli($this->host, $this->user, $this->password);
            if ($conn->connect_error) {
                echo '数据库连接失败,错误信息:' . $conn->connect_error;
            }
            // 选择数据库
            $conn->select_db($this->dbname);
            // 设置字符集
            $conn->set_charset('utf8');
            $this->db = $conn;
        }
        // 禁止克隆
        private function __clone()
        { }
        // 单例模式
        public static function init(){
            // 判断静态变量$c是否是本类的实例化对象
            if(!self::$c instanceof self){
                self::$c = new self;
            }
            return self::$c;
        }
        
        // 这里写各种对数据库操作的方法,例如增删改查
    
        // 关闭数据库
        function __destruct()
        {
           $this->db->close(); 
        }
    }

      调用方法

      

    $db = DB::init();
    // 下面跟着要调用的操作数据库方法 例如
    $res = $db->queryall();
    ╰︶﹉⋛⋋⊱⋋๑๑⋌⊰⋌⋚﹉︶╯
  • 相关阅读:
    day52—JavaScript拖拽事件的应用(自定义滚动条)
    day51—JavaScript绑定事件
    day50—JavaScript鼠标拖拽事件
    day49—JavaScript阻止浏览器默认行为
    day48—JavaScript键盘事件
    day47—JavaScript事件基础应用
    day41—JavaScript运动的停止条件
    Java Web项目使用图形验证码 — Kaptcha
    Disconf-Web管理端安装
    Git基本常用指令
  • 原文地址:https://www.cnblogs.com/zhangcheng001/p/11253849.html
Copyright © 2020-2023  润新知