zoukankan      html  css  js  c++  java
  • php单例模式数据库类的简单封装

    项目中经常要调用php连接数据库(没有使用PDO连接),使用设计模式中的单例模式做了简单的封装。另外可以做为客户端app连接数据库调用。

    闲话少叙,具体如下:

     1 <?php
     2 
     3 class Db {
     4     static private $_instance;
     5     static private $_connectSource;
     6     private $_dbConfig = array(
     7         'host' => '127.0.0.1',
     8         'user' => 'root',
     9         'password' => '',
    10         'database' => '',
    11     );
    12 
    13     private function __construct() {
    14     }
    15 
    16     static public function getInstance() {
    17         if(!(self::$_instance instanceof self)) {
    18             self::$_instance = new self();
    19         }
    20         return self::$_instance;
    21     }
    22 
    23     public function connect() {
    24         if(!self::$_connectSource) {
    25             self::$_connectSource = @mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);    
    26 
    27             if(!self::$_connectSource) {
    28                 throw new Exception('mysql connect error ' . mysql_error());
    29                 //die('mysql connect error' . mysql_error());
    30             }
    31             
    32             mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
    33             mysql_query("set names UTF8", self::$_connectSource);
    34         }
    35         return self::$_connectSource;
    36     }
    37 }
  • 相关阅读:
    Eclipse中显示行号
    PeerSim中一些自己的理解
    迄今为止看过的书籍
    Java程序跨平台运行
    Linux下在PeerSim中运行Chord源代码
    在Eclipse中运行PeerSim的例子
    Ubuntu下安装Java
    Eclipse中自动调整代码
    Eclipse中Outline里各种图标的含义
    Java是如何运行的
  • 原文地址:https://www.cnblogs.com/luchongjian/p/4736528.html
Copyright © 2011-2022 走看看