UNIX艺术

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

下面类借助单例模式在Yii中实现访问多个数据库:

View Code
 1 <?php
 2 
 3 /*
 4  * 访问多个MySQL数据库
 5  * @Author: jinhuawang76
 6  * @Date: 2013/1/12
 7  */
 8 
 9 /**
10  * Description of MySQLInstance
11  *
12  * @author Administrator
13  */
14 class MySQLInstance {
15 
16     private static $_instance;
17     private $con; // mysql数据库连接
18 
19     /**
20      *  私有化构造函数,防止外界实例化对象
21      */
22 
23     private function __construct() {
24         
25     }
26 
27     /**
28      *  私有化克隆函数,防止外界克隆对象
29      */
30     private function __clone() {
31         
32     }
33 
34     static function instance() {
35         if (!self::$_instance) {
36             self::$_instance = new self();
37         }
38         return self::$_instance;
39     }
40 
41     /**
42      * 初始化连接MySQL数据库
43      * return 0 表示成功,否则返回错误字符串
44      * @param type $user
45      * @param type $password
46      * @param type $host
47      * @param type $port
48      */
49     function init($user, $password, $db, $host = null, $port = null) {
50         $server = "127.0.0.1";
51         if ($host != null) {
52             $server = $host;
53         }
54         if ($port != null) {
55             $server .= ':' . $port;
56         }
57 
58         $this->con = mysql_connect($server, $user, $password);
59         if (!$this->con) {
60             return false;
61         }
62 
63         if (!mysql_select_db($db, $this->con)) {
64             return false;
65         }
66 
67         return true;
68     }
69 
70     /**
71      * 执行mysql_query,返回数组
72      * @param type $sql
73      */
74     public function runQuery($sql) {
75         if ($this->con == null) {
76             return null;
77         }
78         mysql_query("SET NAMES UTF8");
79         $rs = mysql_query($sql, $this->con);
80         if (!$rs) {
81             return null;
82         }
83         $ret = array();
84         while ($row = mysql_fetch_array($rs)) {
85             $ret[] = $row;
86         }
87         mysql_free_result($rs);
88         return $ret;
89     }
90 
91     function __destruct() {
92         if ($this->con != null) {
93             mysql_close($this->con);
94         }
95     }
96 
97 }
98 
99 ?>

 

posted on 2013-02-17 11:06  jinhuawang76  阅读(216)  评论(0编辑  收藏  举报