设置数据库连接必备参数
@param array  $dbconfig   数据库连接配置信息
@return object
10296
public function setDbConn($dbconfig = [])
    {
        if (empty($dbconfig)) {
            $this->dbconfig = config('database');
            //$this->dbconfig = Config::get('database');
        } else {
            $this->dbconfig = $dbconfig;
        }
        return $this;
    }
680057
public static function getDbo()
	{
		if (!self::$database)
		{
			//get config values

			$host = Config::get()->get('database.host');
			$user = Config::get()->get('database.user');
			$password = Config::get()->get('database.password');
			$database = Config::get()->get('database.name');
			$prefix = Config::get()->get('database.prefix');
			$driver = Config::get()->get('database.driver');
			$debug = Config::get()->get('database.debug');

			//added extra code to prevent error when $driver is incorrect

			$options = array('driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix);

			self::$database = DatabaseFactory::getInstance()->getDriver($driver, $options);

			//get the debug configuration setting
			self::$database->setDebug(Config::get()->get('debug'));
		}
		return self::$database;
	}
989815
static public function getInstance($config=array()) {
        $md5    =   md5(serialize($config));
        if(!isset(self::$instance[$md5])) {
            // 解析连接参数 支持数组和字符串
            $options    =   self::parseConfig($config);
            // 兼容mysqli
            if('mysqli' == $options['type']) $options['type']   =   'mysql';
            // 如果采用lite方式 仅支持原生SQL 包括query和execute方法
            $class  =   !empty($options['lite'])?  'Think\Db\Lite' :   'Think\\Db\\Driver\\'.ucwords(strtolower($options['type']));
            if(class_exists($class)){
                self::$instance[$md5]   =   new $class($options);
            }else{
                // 类没有定义
                E(L('_NO_DB_DRIVER_').': ' . $class);
            }
        }
        self::$_instance    =   self::$instance[$md5];
        return self::$_instance;
    }
750526
public function init(array $config = [])
    {
        $config = $config ?: $this->config;

        $isDoStart = false;
        if (isset($config['use_trans_sid'])) {
            ini_set('session.use_trans_sid', $config['use_trans_sid'] ? 1 : 0);
        }

        // 启动session
        if (!empty($config['auto_start']) && PHP_SESSION_ACTIVE != session_status()) {
            ini_set('session.auto_start', 0);
            $isDoStart = true;
        }

        if (isset($config['prefix'])) {
            $this->prefix = $config['prefix'];
        }

        if (isset($config['use_lock'])) {
            $this->lock = $config['use_lock'];
        }

        if (isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])) {
            session_id($_REQUEST[$config['var_session_id']]);
        } elseif (isset($config['id']) && !empty($config['id'])) {
            session_id($config['id']);
        } else {
            session_id(WorkerHttp::sessionId());
        }

        if (isset($config['name'])) {
            WorkerHttp::sessionName($config['name']);
        }

        if (isset($config['path'])) {
            WorkerHttp::sessionSavePath($config['path']);
        }

        if (isset($config['domain'])) {
            ini_set('session.cookie_domain', $config['domain']);
        }

        if (isset($config['expire'])) {
            ini_set('session.gc_maxlifetime', $config['expire']);
            ini_set('session.cookie_lifetime', $config['expire']);
        }

        if (isset($config['secure'])) {
            ini_set('session.cookie_secure', $config['secure']);
        }

        if (isset($config['httponly'])) {
            ini_set('session.cookie_httponly', $config['httponly']);
        }

        if (isset($config['use_cookies'])) {
            ini_set('session.use_cookies', $config['use_cookies'] ? 1 : 0);
        }

        if (isset($config['cache_limiter'])) {
            session_cache_limiter($config['cache_limiter']);
        }

        if (isset($config['cache_expire'])) {
            session_cache_expire($config['cache_expire']);
        }

        if (!empty($config['type'])) {
            // 读取session驱动
            $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\session\\driver\\' . ucwords($config['type']);

            // 检查驱动类
            if (!class_exists($class) || !session_set_save_handler(new $class($config))) {
                throw new ClassNotFoundException('error session handler:' . $class, $class);
            }
        }

        if ($isDoStart) {
            $this->start();
        } else {
            $this->init = false;
        }

        return $this;
    }
409175
private function getDblibDsn(array $config)
    {
        $arguments = [
            'host'   => $config['host'] . ':' . $config['port'],
            'dbname' => $config['database'],
        ];

        if (isset($config['appname'])) {
            $arguments['appname'] = $config['appname'];
        }

        if (isset($config['charset'])) {
            $arguments['charset'] = $config['charset'];
        }

        return $this->buildConnectString('dblib', $arguments);
    }
1061581
public function init($dbConfig)
    {
        $profiler = new Profiler();

        if (isset($this->drivers[$dbConfig['driver']])) {
            $driverClass          = $this->drivers[$dbConfig['driver']];
            self::$driverInstance = $driverClass::getInstance();

            $profiler->getTimer()->start();
            self::$driverInstance->setup($dbConfig);

            $profilerOptions = [
                'type' => 'connection',
                'time' => $profiler->getTimer()->calculate()
            ];

            $profiler->setOptions('dbConnection', $profilerOptions);
            Safan::handler()->getObjectManager()->setObject('gapOrmProfiler', $profiler);
        } else {
            throw new DriverNotFound($dbConfig['driver']);
        }
    }
598880
private function getDbConfig() {
        if (file_exists(MODULES_DIR . DS . $this->currentRoute['module'] . '/Config/database.php')) {
            $dbConfig = require_once MODULES_DIR . DS . $this->currentRoute['module'] . '/Config/database.php';

            if (!empty($dbConfig) && is_array($dbConfig)) {
                return $dbConfig;
            } else {
                throw new \Exception(ExceptionMessages::INCORRECT_CONFIG);
            }
        } else {
            if (file_exists(BASE_DIR . '/config/database.php')) {
                $dbConfig = require_once BASE_DIR . '/config/database.php';
                if (!empty($dbConfig) && is_array($dbConfig)) {
                    return $dbConfig;
                } else {
                    throw new \Exception(ExceptionMessages::INCORRECT_CONFIG);
                }
            } else {
                throw new \Exception(ExceptionMessages::DB_CONFIG_NOT_FOUND);
            }
        }
    }
791166
protected function createDatabaseDriver( array $config )
	{
		return new DatabaseStore( DatabaseManager::i()->connection( Arr::get( $config, 'connection' ) ), Encrypter::i(), $config['table'], $this->getPrefix( $config ) );
	}
1172987
public function init($config)
    {
        $this->pdo = null;

        $dns = '';
        if (is_array($config)) {
            $config += array('user' => null, 'password' => null);
            $dns = "{$config['type']}:host={$config['host']};port={$config['port']};dbname={$config['name']}";
        } else if (is_string($config)) {
            $dns = $config;
        } else if ($config instanceof PDO) {
            $this->pdo = $config;
            return $this;
        }

        try {

            // Use pipe for merging fields - sqlite compatibility
            $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode='PIPES_AS_CONCAT'");
            $this->pdo = new PDO($dns, $config['user'], $config['password'], $options);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (Exception $ex) {
            $this->pdo = null;
            throw new RuntimeException('Cannot connect to database: ' . $ex->getMessage());
        }

        return $this;
    }
808007
public function configure($config = [])
    {
        return new static ([
            'driver'   => 'pdo_sqlite',
            'user'     => array_get($config, 'username'),
            'password' => array_get($config, 'password'),
            'prefix'   => array_get($config, 'prefix'),
            'memory'   => $config['database'] == ':memory' ? true : false,
            'path'     => $config['database'] == ':memory' ? null : $config['database']
        ]);
    }
1172219
public function db($conf = '')
    {
        $conf == '' && $conf = $this->getDbConf();
        if (is_array($conf)) {
            $config = $conf;
            $conf = md5(json_encode($conf));
        } else {
            $config = Config::get($conf);
        }
        $config['mark'] = $conf;

        if (isset($this->dbInstance[$conf])) {
            return $this->dbInstance[$conf];
        } else {
            $pos = strpos($config['driver'], '.');
            $this->dbInstance[$conf] = Cml::getContainer()->make('db_' . strtolower($pos ? substr($config['driver'], 0, $pos) : $config['driver']), $config);
            return $this->dbInstance[$conf];
        }
    }
516032
private function buildConnection($connConfig) {
        //基于数组的连接配置
        if (is_array($connConfig)) {
            $pdoProviderClass = $connConfig['pdoProvider'];
            unset($connConfig['pdoProvider']);

            /* @var $conn PDOProviderInterface */
            $pdoProvider = new $pdoProviderClass($connConfig);

            $conn = new Connection($pdoProvider, $this->logger);
            $conn->setTablePrefix($connConfig['tablePrefix']);
        }
        //回调函数
        //回调函数可以接收当前 ConnectionManager 实例作为参数，当然，这个参数是可选的
        elseif ($connConfig instanceof Closure) {
            $callback = $connConfig;
            $refFunc = new ReflectionFunction($callback);
            $conn = $refFunc->getNumberOfParameters() == 1 ? $callback($this) : $callback();
        } else {
            throw new SqlException('连接配置类型错误');
        }

        return $conn;
    }
1039096
static private function parseConfig($config){
        if(!empty($config)){
            if(is_string($config)) {
                return self::parseDsn($config);
            }
            $config =   array_change_key_case($config);
            $config = array (
                'type'          =>  $config['db_type'],
                'username'      =>  $config['db_user'],
                'password'      =>  $config['db_pwd'],
                'hostname'      =>  $config['db_host'],
                'hostport'      =>  $config['db_port'],
                'database'      =>  $config['db_name'],
                'dsn'           =>  isset($config['db_dsn'])?$config['db_dsn']:null,
                'params'        =>  isset($config['db_params'])?$config['db_params']:null,
                'charset'       =>  isset($config['db_charset'])?$config['db_charset']:'utf8',
                'deploy'        =>  isset($config['db_deploy_type'])?$config['db_deploy_type']:0,
                'rw_separate'   =>  isset($config['db_rw_separate'])?$config['db_rw_separate']:false,
                'master_num'    =>  isset($config['db_master_num'])?$config['db_master_num']:1,
                'slave_no'      =>  isset($config['db_slave_no'])?$config['db_slave_no']:'',
                'debug'         =>  isset($config['db_debug'])?$config['db_debug']:APP_DEBUG,
                'lite'          =>  isset($config['db_lite'])?$config['db_lite']:false,
            );
        }else {
            $config = array (
                'type'          =>  C('DB_TYPE'),
                'username'      =>  C('DB_USER'),
                'password'      =>  C('DB_PWD'),
                'hostname'      =>  C('DB_HOST'),
                'hostport'      =>  C('DB_PORT'),
                'database'      =>  C('DB_NAME'),
                'dsn'           =>  C('DB_DSN'),
                'params'        =>  C('DB_PARAMS'),
                'charset'       =>  C('DB_CHARSET'),
                'deploy'        =>  C('DB_DEPLOY_TYPE'),
                'rw_separate'   =>  C('DB_RW_SEPARATE'),
                'master_num'    =>  C('DB_MASTER_NUM'),
                'slave_no'      =>  C('DB_SLAVE_NO'),
                'debug'         =>  C('DB_DEBUG',null,APP_DEBUG),
                'lite'          =>  C('DB_LITE'),
            );
        }
        return $config;
    }
1207556
public function connect(array $config): PDO
    {
        if (isset($config['options']) === false) {
            $config['options'] = [];
        }

        return $this->doConnect($config);
    }
1347345
private static function parseConfig($config)
    {
        if (empty($config)) {
            $config = Container::get('config')->pull('database');
        } elseif (is_string($config) && false === strpos($config, '/')) {
            // 支持读取配置参数
            $config = Container::get('config')->get('database.' . $config);
        }

        if (is_string($config)) {
            return self::parseDsnConfig($config);
        } else {
            return $config;
        }
    }
845668
public function configure($config = [])
    {
        return new static ([
            'driver'      => 'pdo_mysql',
            'host'        => array_get($config, 'host'),
            'dbname'      => array_get($config, 'database'),
            'user'        => array_get($config, 'username'),
            'password'    => array_get($config, 'password'),
            'charset'     => array_get($config, 'charset'),
            'port'        => array_get($config, 'port'),
            'unix_socket' => array_get($config, 'unix_socket'),
            'prefix'      => array_get($config, 'prefix'),
        ]);
    }
905337
public static function load(array $config) {
		assert(key_exists("cache_path", $config), "Cache path not set.");
		assert(key_exists("db", $config), "Database config not set");

		$db_conf = $config['db'];

		$ormMemcache = Persistence\OrmMemcache::init($config['cache_path']);

		$dsn = 'mysql:host=' . $db_conf['host'] . ';dbname=' . $db_conf['db'];
		$options = [
			PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8MB4'",
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
		];
		$pdo = new PDO($dsn, $db_conf['user'], $db_conf['pass'], $options);

		$database = Persistence\Database::init($pdo);
		$databaseAdmin = Persistence\DatabaseAdmin::init($pdo);

		DependencyManager::addDependency($ormMemcache);
		DependencyManager::addDependency($database);
		DependencyManager::addDependency($databaseAdmin);
	}