lithium\data\source\Database::connect()

public method

Connects to the database by creating a PDO intance using the constructed DSN string. Will set general options on the connection as provided (persistence, encoding).

Returns

boolean

Returns true if a database connection could be established, otherwise false.

Source

	public function connect() {
		$this->_isConnected = false;
		$config = $this->_config;

		if (!$config['dsn']) {
			throw new ConfigException('No DSN setup for database connection.');
		}
		$dsn = $config['dsn'];

		$options = $config['options'] + [
			PDO::ATTR_PERSISTENT => $config['persistent'],
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
		];

		try {
			$this->connection = new PDO($dsn, $config['login'], $config['password'], $options);
		} catch (PDOException $e) {
			preg_match('/SQLSTATE\[(.+?)\]/', $e->getMessage(), $code);
			$code = empty($code[1]) ? 0 : $code[0];
			switch (true) {
				case $code === 'HY000' || substr($code, 0, 2) === '08':
					$msg = "Unable to connect to host `{$config['host']}`.";
					throw new NetworkException($msg, null, $e);
				break;
				case in_array($code, ['28000', '42000']):
					$msg = "Host connected, but could not access database `{$config['database']}`.";
					throw new ConfigException($msg, null, $e);
				break;
			}
			throw new ConfigException($e->getMessage(), null, $e);
		}
		$this->_isConnected = true;

		if ($this->_config['encoding'] && !$this->encoding($this->_config['encoding'])) {
			return false;
		}
		return $this->_isConnected;
	}