Connects to the database using options in the given configuration array.

@return bool True if connecting to the DataSource succeeds, else false
342643
protected function _connect() {
		$unixSocket = $this->config['unix_socket'];
		$persistent = $this->config['persistent'];
		$host = $this->config['host'];
		$port = $this->config['port'];
		$timeout = $this->config['timeout'];

		if ($unixSocket) {
			return $this->_connection->connect($unixSocket);
		} elseif ($persistent) {
			return $this->_connection->pconnect($host, $port, $timeout, $persistent);
		} else {
			return $this->_connection->connect($host, $port, $timeout);
		}
	}
1087722
private function connect()
    {
        // Connecting with PDO.
        try {
            switch ($this->dbType) {
                case 'sqlite':
                    $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings);
                    break;
                case 'mysql':
                case 'pgsql':
                case 'dblib':
                    $this->dbHandler = @new PDO(
                        $this->dsn,
                        $this->user,
                        $this->pass,
                        $this->pdoSettings
                    );
                    // Execute init commands once connected
                    foreach ($this->dumpSettings['init_commands'] as $stmt) {
                        $this->dbHandler->exec($stmt);
                    }
                    // Store server version
                    $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION);
                    break;
                default:
                    throw new Exception("Unsupported database type (".$this->dbType.")");
            }
        } catch (PDOException $e) {
            throw new Exception(
                "Connection to ".$this->dbType." failed with message: ".
                $e->getMessage()
            );
        }

        if (is_null($this->dbHandler)) {
            throw new Exception("Connection to ".$this->dbType."failed");
        }

        $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
        $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings);
    }
33315
public function connect() {
		if (!$this->connected) {
			if ($this->config['host']{0} == '/') {
				$connector = $this->config['driver'].':unix_socket='.$this->config['host'].';dbname='.$this->config['db'];
			} else {
				$connector = $this->config['driver'].':host='.$this->config['host'].';dbname='.$this->config['db'];
			}
			
			// sqlite
			if ($this->config['driver'] == 'sqlite') {
				$connector = $this->config['driver'].':'.$this->config['file'].'';
			}
			
			parent::__construct($connector, $this->config['user'], $this->config['pass']);

			$this -> setAttribute(\PDO::ATTR_CASE, \PDO::CASE_NATURAL); // leave column names as returned by the database driver
			$this -> setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); // on errors we want to get \Exceptions

			// set encoding
			if (isset($this->config['encoding']) && $this->config['driver'] != 'sqlite') {
				parent::exec('SET NAMES '.$this->config['encoding']);
			}

			$this->connected = true;
		}
	}
867946
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Build the connection configuration array.
		$config = array(
			'Database' => $this->options['database'],
			'uid' => $this->options['user'],
			'pwd' => $this->options['password'],
			'CharacterSet' => 'UTF-8',
			'ReturnDatesAsStrings' => true);

		// Make sure the SQLSRV extension for PHP is installed and enabled.
		if (!static::isSupported())
		{
			throw new \RuntimeException('PHP extension sqlsrv_connect is not available.');
		}

		// Attempt to connect to the server.
		if (!($this->connection = @ sqlsrv_connect($this->options['host'], $config)))
		{
			throw new \RuntimeException('Database sqlsrv_connect failed');
		}

		// Make sure that DB warnings are not returned as errors.
		sqlsrv_configure('WarningsReturnAsErrors', 0);

		// If auto-select is enabled select the given database.
		if ($this->options['select'] && !empty($this->options['database']))
		{
			$this->select($this->options['database']);
		}
	}
417540
public function checkDbConfig() {
        if (!$this->dbConfig || !$this->db) {
            $dbConfigs = array_keys(get_class_vars('DATABASE_CONFIG'));

            $this->out('Available database configurations:');

            foreach ($dbConfigs as $i => $db) {
                $this->out(sprintf('[%s] <info>%s</info>', $i, $db));
            }

            $this->out();

            $answer = $this->in('Which database should the queries be executed in?', array_keys($dbConfigs));

            if (isset($dbConfigs[$answer])) {
                $this->setDbConfig($dbConfigs[$answer]);
            } else {
                $this->checkDbConfig();
            }
        }

        $this->out(sprintf('Database Config: <info>%s</info>', $this->dbConfig));

        $answer = strtoupper($this->in('Is this correct?', array('Y', 'N')));

        if ($answer === 'N') {
            $this->dbConfig = null;
            $this->checkDbConfig();
        }

        // Check that database is connected
        if (!$this->db->isConnected()) {
            $this->err(sprintf('<error>Database connection for %s failed</error>', $this->dbConfig));
            return false;
        }

        $this->out('<success>Database check successful, proceeding...</success>');
        return true;
    }
1088977
private function _connected() {

        // if there's no connection to a MySQL database
        if (!$this->connection) {

            // we need this because it is the only way we can set the connection options (if any)
            $this->connection = mysqli_init();

            // if we have any options set
            if (!empty($this->options))

                // iterate over the set options
                foreach ($this->options as $option => $value)

                    // set each option
                    $this->connection->options($option, $value) ||

                        // log if there's a bogus option/value
                        $this->_log('errors', array(

                            'message'   => sprintf($this->language['invalid_option'], $option),

                        ));

            // connect to the MySQL server
            @mysqli_real_connect(
                $this->connection,
                $this->credentials['host'],
                $this->credentials['user'],
                $this->credentials['password'],
                $this->credentials['database'],
                $this->credentials['port'],
                $this->credentials['socket']
            );

            // tries to connect to the MySQL database
            if (mysqli_connect_errno())

                // if connection could not be established
                // save debug information
                return $this->_log('errors', array(

                    'message'   => $this->language['could_not_connect_to_database'],
                    'error'     => mysqli_connect_error(),

                ));

            // if caching is to be done to a memcache server and we don't yet have a connection
            if (!$this->memcache && $this->memcache_host !== false && $this->memcache_port !== false) {

                // if memcache extension is installed
                if (class_exists('Memcache')) {

                    // instance to the memcache object
                    $memcache = new Memcache();

                    // try to connect to the memcache server
                    if (!$memcache->connect($this->memcache_host, $this->memcache_port))

                        // if connection could not be established, save debug information
                        $this->_log('errors', array(

                            'message'   => $this->language['could_not_connect_to_memcache_server']

                        ));

                    else $this->memcache = $memcache;

                // if memcache extension is not installed
                } else

                    // if connection could not be established, save debug information
                    $this->_log('errors', array(

                        'message'   => $this->language['memcache_extension_not_installed']

                    ));

            }

        }

        // return TRUE if there is no error
        return true;

    }
239521
private function _connected (array $db)
    {
        try {
            $connection = mysqli_connect ($db['host'], $db['username'], $db['password'], $db['name']);

            return $connection ? true : false;
        } catch (\Exception $e) {
            return false;
        }
    }
770946
private function _connect()
    {
        if (empty($this->_config))
            throw new \Exception('Empty connection settings provided'); 
        
        $port = $this->_config->getPort();
        $port = !empty($port) ? $port : 3306;
        $dsn = $this->_config->getType().':host='.$this->_config->getHost().';port='.$port.';dbname='.$this->_config->getName();
        // Create a PDO Instance for this user + database combination
        try {
            $this->_conn = new \PDO($dsn, $this->_config->getUser(), $this->_config->getPassword());
        } catch(\PDOException $pe) {
            throw new \RuntimeException("Cannot connect to DB '".$this->_config->getName().
                "' with user '".$this->_config->getUser()."'".PHP_EOL."Message: ".$pe->getMessage());
        }

        $this->_conn->setAttribute(\PDO::ATTR_PERSISTENT, false);
        $this->_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->_conn->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'");
        $this->_conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $this->_conn->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING);
        $this->_conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
    }
831094
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Make sure the PDO extension for PHP is installed and enabled.
		if (!self::isSupported())
		{
			throw new \RuntimeException('PDO Extension is not available.', 1);
		}

		// Find the correct PDO DSN Format to use:
		switch ($this->options['driver'])
		{
			case 'cubrid':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 33000;

				$format = 'cubrid:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'dblib':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1433;

				$format = 'dblib:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'firebird':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 3050;

				$format = 'firebird:dbname=#DBNAME#';

				$replace = array('#DBNAME#');
				$with = array($this->options['database']);

				break;

			case 'ibm':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 56789;

				if (!empty($this->options['dsn']))
				{
					$format = 'ibm:DSN=#DSN#';

					$replace = array('#DSN#');
					$with = array($this->options['dsn']);
				}
				else
				{
					$format = 'ibm:hostname=#HOST#;port=#PORT#;database=#DBNAME#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#');
					$with = array($this->options['host'], $this->options['port'], $this->options['database']);
				}

				break;

			case 'informix':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1526;
				$this->options['protocol'] = (isset($this->options['protocol'])) ? $this->options['protocol'] : 'onsoctcp';

				if (!empty($this->options['dsn']))
				{
					$format = 'informix:DSN=#DSN#';

					$replace = array('#DSN#');
					$with = array($this->options['dsn']);
				}
				else
				{
					$format = 'informix:host=#HOST#;service=#PORT#;database=#DBNAME#;server=#SERVER#;protocol=#PROTOCOL#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#', '#SERVER#', '#PROTOCOL#');
					$with = array($this->options['host'], $this->options['port'], $this->options['database'], $this->options['server'], $this->options['protocol']);
				}

				break;

			case 'mssql':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1433;

				$format = 'mssql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'mysql':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 3306;

				$format = 'mysql:host=#HOST#;port=#PORT#;dbname=#DBNAME#;charset=#CHARSET#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#', '#CHARSET#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database'], $this->options['charset']);

				break;

			case 'oci':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1521;
				$this->options['charset'] = (isset($this->options['charset'])) ? $this->options['charset'] : 'AL32UTF8';

				if (!empty($this->options['dsn']))
				{
					$format = 'oci:dbname=#DSN#';

					$replace = array('#DSN#');
					$with = array($this->options['dsn']);
				}
				else
				{
					$format = 'oci:dbname=//#HOST#:#PORT#/#DBNAME#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#');
					$with = array($this->options['host'], $this->options['port'], $this->options['database']);
				}

				$format .= ';charset=' . $this->options['charset'];

				break;

			case 'odbc':
				$format = 'odbc:DSN=#DSN#;UID:#USER#;PWD=#PASSWORD#';

				$replace = array('#DSN#', '#USER#', '#PASSWORD#');
				$with = array($this->options['dsn'], $this->options['user'], $this->options['password']);

				break;

			case 'pgsql':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 5432;

				$format = 'pgsql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'sqlite':
				if (isset($this->options['version']) && $this->options['version'] == 2)
				{
					$format = 'sqlite2:#DBNAME#';
				}
				else
				{
					$format = 'sqlite:#DBNAME#';
				}

				$replace = array('#DBNAME#');
				$with = array($this->options['database']);

				break;

			case 'sybase':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1433;

				$format = 'mssql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			default:
				throw new \UnexpectedValueException('The ' . $this->options['driver'] . ' driver is not supported.');
		}

		// Create the connection string:
		$connectionString = str_replace($replace, $with, $format);

		try
		{
			$this->connection = new \PDO(
				$connectionString,
				$this->options['user'],
				$this->options['password'],
				$this->options['driverOptions']
			);
		}
		catch (\PDOException $e)
		{
			throw new \RuntimeException('Could not connect to PDO' . ': ' . $e->getMessage(), 2, $e);
		}
	}
1023139
protected function getDatabaseConnections()
    {
        $configFile = $this->findDatabaseFile();
        
        if (!$configFile) {
            return false;
        }
        
        switch (substr($configFile, -3)) {
            case 'php':
                $connections = require $configFile;
                break;
            
            case 'yml':
                $connections = Yaml::readFile($configFile);
                break;
        }
        
        return $connections;
    }
1246503
private function connect()
    {
        if (!$this->isConnected) {
            parent::__construct(
                $this->dsn,
                $this->server->getUsername(),
                $this->server->getPassword(),
                $this->driverOptions
            );
            parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            parent::setAttribute(
                PDO::ATTR_STATEMENT_CLASS,
                [__NAMESPACE__ . '\\' . self::PDO_STATEMENT_CLASS, [$this]]
            );

            $this->isConnected = true;
        }
    }
663425
public function connect()
    {
        $options = & $this->options;
        
        try {
            if (!$this->connection && !@$this->connection->sqlstate) {
                if (isset($options['dsn'])) {
                    $this->connection = new \PDO($options['dsn']);
                } else {
                    if ($options['dbtype'] === 'sqlite') {
                        $this->dsn = $options['dsn'] = $options['dbtype'] . ':' . $options['database'];
                        $this->connection = new \PDO($options['dsn']);
                    } else {
                        if (!isset($options['host']) || !isset($options['username']) || !isset($options['password'])) {
                            throw new Exception('Error: The proper database credentials were not passed.');
                        }
                        if ($options['dbtype'] === 'sqlsrv') {
                            $options['dsn'] = $options['dbtype'] . ':Server=' . $options['host'] . ';Database=' . $options['database'];
                        } else {
                            $options['dsn'] = $options['dbtype'] . ':host=' . $options['host'] . ';dbname=' . $options['database'];
                        }
                        $this->dsn = & $options['dsn'];
                        $this->connection = new \PDO($this->dsn, $options['username'], $options['password']);
                    }
                }
            }
        } catch (\PDOException $e) {
            throw new Exception('Error: Could not connect to database. ' . $e->getMessage());
        }
    }
498346
public function connect() {
		try {
			$this->_connect ();
			return true;
		} catch ( \PDOException $e ) {
			throw new DBException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
		}
	}
618545
protected function _connect()
    {
        if ($this->_connection) {
            return;
        }

        if (!empty($this->_config['charset'])) {
            $initCommand = "SET NAMES '" . $this->_config['charset'] . "'";
            $this->_config['driver_options'][1002] = $initCommand; // 1002 = PDO::MYSQL_ATTR_INIT_COMMAND
        }

        parent::_connect();
    }
1059329
public function connect()
    {
        try {
            $this->instance = DriverManager::getConnection($this->config, new Configuration());
            $this->createSchema();

            return true;
        } catch (DBALException $e) {
            throw new DriverConnectionException($e->getMessage());
        }
    }
711361
protected function _connectdb($notProposeChangeConfig = false) {
		$result = true;
		$this->out(__d('cake_installer', 'Checking database connections'));
		$this->hr();

		$this->out(__d('cake_installer', 'Checking database configuration file'));
		$this->hr();
		$this->waiting->animateMessage();
		$connections = $this->InstallerCheck->checkConnectDb($this->path);
		if ($connections !== null) {
			$state = '<success>' . __d('cake_installer', 'Ok') . '</success>';
		} else {
			$state = '<error>' . __d('cake_installer', 'Bad') . '</error>';
		}
		$state = '[' . $state . ']';
		$message = ' * ' . __d('cake_installer', 'Database configuration file');
		$formattedMessage = $this->state->getState($message, $state, $this->maxWidth - 1);
		$this->waiting->hideMessage();
		$this->out($formattedMessage, 1);
		$this->hr();
		if ($connections !== null) {
			$this->out(__d('cake_installer', 'Checking database connections'), 1);
			$this->hr();
			$messages = [];
			$this->waiting->animateMessage();
			foreach ($connections as $connectionName => $connectionState) {
				$errorMessages = [];
				if ($connectionState === true) {
					$state = '<success>' . __d('cake_installer', 'Ok') . '</success>';
				} else {
					if (is_array($connectionState)) {
						$shell = $this;
						array_walk(
							$connectionState,
							function (&$value) use ($shell) {
								$value = '<debug>' . $shell->wrapText($value, ['width' => $shell->maxWidth]) . '</debug>';
							}
						);
						$errorMessages = $connectionState;
					}
					$state = '<error>' . __d('cake_installer', 'Bad') . '</error>';
					$result = false;
				}
				$state = '[' . $state . ']';
				$message = ' * ' . __d('cake_installer', 'Checking database connection: \'%s\'', $connectionName);
				$messages[] = $this->state->getState($message, $state, $this->maxWidth - 1);
				if (!empty($errorMessages)) {
					$messages = array_merge($messages, $errorMessages);
				}
				$this->waiting->animateMessage();
			}
			$this->waiting->hideMessage();
			$this->out($messages, 1);
			$this->hr();
		}

		if ($result) {
			$this->out('<success>' . __d('cake_installer', 'Check completed successfully.') . '</success>');
		} else {
			$this->out('<error>' . __d('cake_installer', 'Check completed unsuccessfully.') . '</error>');
			if ($notProposeChangeConfig || (!$notProposeChangeConfig && $this->_checkSure(__d('cake_installer', 'Change database connections?')))) {
				$result = $this->_configdb($notProposeChangeConfig);
			}
		}

		return $result;
	}
125878
public function tryConnect() {
		if ($this->db_connected) {
			return TRUE;
		}
		if (!class_exists('mysqli')) {
			BLog::addToLog($this->logsuffix . ': MySQLi class not found', LL_ERROR);
			return FALSE;
		}
		$this->mysqli = new \mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name, $this->db_port);
		if ((empty($this->mysqli)) || (mysqli_connect_errno())) {
			BLog::addToLog($this->logsuffix . ': ' . mysqli_connect_error(), LL_ERROR);
			return FALSE;
		}
		if (!$this->mysqli->set_charset("utf8")) return FALSE;
		$this->db_connected = TRUE;
		return TRUE;
	}