/** * 初始化一个连接 * * @param string $key * 数据库配置的连接源键 * @return void */ private static function loadSelection($key) { // 判断是否已经选择mysql数据库驱动 if (!isset(self::$connType)) { if (extension_loaded('pdo_mysql')) { self::$connType = 1; } elseif (class_exists('mysqli')) { self::$connType = 2; } elseif (function_exists('mysql_connect')) { self::$connType = 3; } else { ErrorHandler::handlerErrmsg(500, 'mysql driver not found'); } } // 连接数据库 if (!isset(self::$connArr[$key])) { // 加载数据库配置 $config = self::$config; $confPath = self::getConfPath(); if (empty($config) && is_file($confPath)) { include $confPath; self::$config = $config; } // 随机取出一条连接 $rand_key = array_rand($config[$key]); $tmpConfig = $config[$key][$rand_key]; $initSql = 'SET NAMES utf8'; if (isset($tmpConfig['charset'])) { $initSql = 'SET NAMES ' . $tmpConfig['charset']; } // 根据驱动类型,保存连接对象 if (self::$connType == 1) { // pdo $dsn = sprintf('mysql:host=%s;port=%d;dbname=%s', $tmpConfig['host'], $tmpConfig['port'], $tmpConfig['dbname']); try { $conn = new PDO($dsn, $tmpConfig['user'], $tmpConfig['pass']); $conn->exec($initSql); self::$connArr[$key] = $conn; } catch (Exception $e) { ErrorHandler::handlerErrmsg(500, 'connect error to key@' . $key . ',' . $e->getMessage()); } } elseif (self::$connType == 2) { // mysqli $db = @new mysqli($tmpConfig['host'], $tmpConfig['user'], $tmpConfig['pass'], $tmpConfig['dbname'], $tmpConfig['port']); if ($db->connect_error) { ErrorHandler::handlerErrmsg(500, 'connect error to key@' . $key . ', (' . $db->connect_errno . ') ' . $db->connect_error); } $db->query($initSql); self::$connArr[$key] = $db; } elseif (self::$connType == 3) { // mysql $link = @mysql_connect($tmpConfig['host'] . ':' . $tmpConfig['port'], $tmpConfig['user'], $tmpConfig['pass']); if (!$link) { ErrorHandler::handlerErrmsg(500, 'connect error to key@' . $key . ', ' . mysql_error()); } mysql_select_db($tmpConfig['dbname']); mysql_query($initSql, $link); self::$connArr[$key] = $link; } } }