Create a new database connection

@throws PDOException If there is unable to connect to database
@throws Exception If an error occurs

@return PDO
18588
public function getConnection() {
		try {
			$pdo = null;

			switch($this->driver){
				case "pdo_mysql": // MySQL Database
					$pdo = new PDO("mysql:host=".$this->host.";dbname=".$this->database.";charset=utf8", $this->user, $this->password);
					break;
				case "pdo_sqlserver": // SQL Server Database
					$pdo = new PDO("sqlsrv:Server=".$this->host.";Database=".$this->database, $this->user, $this->password);
					break;
				case "pdo_sqlite": // SQLite Database
				    $pdo = new PDO("sqlite:{$this->database}");
					break;
				case "pdo_pgsql": // PostgreSQL Database
				    $pdo = new PDO("pgsql:dbname={$this->database};host={$this->host}", $this->user, $this->password);
				    break;
				case "pdo_oci": // Oracle Database
					$tns = "oci:dbname=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (Host = {$this->host}) (Port = {$this->port}))) (CONNECT_DATA = (SERVICE_NAME = {$this->database})))";
					$pdo = new PDO($tns, $this->user, $this->password);
					break;
				default:
					throw new  Exception("Database driver not defined");
				}

				if (count($this->attributes) > 0) {
					foreach ($this->attributes as $key => $value) {
						$pdo->setAttribute($key, $value);
					}
				}

				$this->pdo = $pdo;

				return $pdo;

		} catch (PDOException $e) {
			throw new PDOException('Unable to connect to database, errorMessage = '.$e->getMessage());
		} catch (Exception $e) {
			throw new Exception('Internal error, errorMessage = '.$e->getMessage());
		}
	}
335905
public static function doConnect()
        {
            if (!\class_exists('\\PDO')) {
                throw new Exception('B2DB needs the PDO PHP libraries installed. See http://php.net/PDO for more information.');
            }
            try {
                $uname = self::getUsername();
                $pwd = self::getPassword();
                $dsn = self::getDSN();
                if (self::$db_connection instanceof PDO) {
                    self::$db_connection = null;
                }
                self::$db_connection = new PDO($dsn, $uname, $pwd);
                if (!self::$db_connection instanceof PDO) {
                    throw new Exception('Could not connect to the database, but not caught by PDO');
                }
        switch (self::getDriver())
        {
            case self::DRIVER_MYSQL:
                self::getDBLink()->query('SET NAMES UTF8');
                break;
            case self::DRIVER_POSTGRES:
                self::getDBlink()->query('set client_encoding to UTF8');
                break;
        }
            } catch (PDOException $e) {
                throw new Exception("Could not connect to the database [" . $e->getMessage() . "], dsn: ".self::getDSN());
            } catch (Exception $e) {
                throw $e;
            }
        }
1124337
private function connect()
    {
        $port = isset($this->_args['port']) && $this->_args['port'] ? $this->_args['port'] : 3306;
        $dsn = "mysql:host={$this->_args['host']};port={$port};dbname={$this->_args['dbname']}";
        $username = $this->_args['username'];
        $password = $this->_args['password'];

        // TODO: Move to use the follow: PDO::ATTR_EMULATE_PREPARES to 'false'
        // For security reason
        $options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];

        /*\
         * The latter can be fixed by turning off emulation
         * and using the DSN charset attribute instead of SET NAMES.
         * The former is tricky, because you have no concept for safely
         * dealing with identifiers (they're just dumped straight into the query).
         * One possible approach would be to wrap all identifiers in backticks
         * while escaping all backticks within the identifiers (through doubling).
         * Whether this actually works in all cases is an open question, though.
        \*/

        try {
            $this->_pdo = new PDO($dsn, $username, $password, $options);
        } catch (PDOException $ex) {
            $this->_database->error('connect', $ex);
        }

        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
1304265
public static function create($database = [])
    {
        try {
            $driver = isset($database['driver']) ? ucwords($database['driver']) : "";
            $className = __NAMESPACE__ . "\\Engines\\" . $driver;
            if (class_exists($className)) {
                return new $className($database);
            } else {
                throw new \RuntimeException("Unidentified connection engine $className.");
            }
        } catch (\PDOException $e) {
            throw new \RuntimeException('Problem connecting to the database: ' . $e->getMessage());
        }
    }
287799
public function connection()
    {
        if (!is_object($this->db)) {
            $this->db = new \FaaPz\PDO\Database(
                $this->database['driver'] . ':host=' . $this->database['host'] . ';port=' . $this->database['port'] . ';dbname=' . $this->database['database'] . ';charset=' . $this->database['charset'] . ';collation=' . $this->database['collation'] . ';prefix=' . $this->database['prefix'],
                $this->database['username'],
                $this->database['password'],
                $this->database['options']
            );
            $this->db->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
        }

        return $this;
    }
158493
public function create()
    {
        try {
            $schema = explode(';', str_replace(PHP_EOL, '', $this->getSchema()));
            array_pop($schema);

            # db structure
            $sql = array_shift($schema);
            $this->db->query($sql . ';');

            # indecies
            foreach($schema as $sql) {
                $this->db->query($sql . ';');
            }
        } catch(Exception $e) {
            throw new Exception($e->getMessage(), 1);
        }
    }
78562
public function pdoWithoutDB()
    {
        $this->checkConfiguration();

        try {
            return new PDO(
                $this->buildDsn(false),
                $this->config['username'],
                $this->config['password']
            );
        } catch (Exception $e) {
            throw new RuntimeException(static::E_CONNECT);
        }
    }
244046
private function connect()
    {
        if ($this->isConnected()) {
            return $this;
        }

        $connectionString = sprintf(
            'host=%s port=%d dbname=%s user=%s password=%s sslmode=%s',
            $this->host,
            $this->port,
            $this->dbName,
            $this->username,
            $this->password,
            $this->sslMode ? 'require' : 'disable'
        );

        $this->pgConn = pg_connect($connectionString);
        if ($this->pgConn === false) {
            throw $this->createException('Can`t connect');
        }

        $this->pendingConnection = false;

        return $this;
    }
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);
    }
1320933
public function getConnection()
    {
        if (! $this->connection) {
            list($dns, $username, $password) = $this->connectionString();

            $this->setConnection(new \PDO($dns, $username, $password));
        }

        return $this->connection;
    }
1042351
protected function createPdoInstance()
    {
        $pdoClass = $this->pdoClass;
        if (!class_exists($pdoClass)) {
            throw new Exception(str_cover('PDO连接库"{className}"不存在', [
                '{className}' => $pdoClass
            ]), 101300104);
        }
        // 创建 PDO 实例
        @$instance = new $pdoClass($this->dsn, $this->username, $this->password);
        if (!$instance) {
            throw new Exception('PDO连接数据库失败.', 101300103);
        }
        return $instance;
    }
1013525
public function Connection() {
      $this->_IsPersistent = GetValue(PDO::ATTR_PERSISTENT, $this->ConnectionOptions, FALSE);
      if(!is_object($this->_Connection)) {
         try {
            $this->_Connection = new PDO(strtolower($this->Engine) . ':' . $this->Dsn, $this->User, $this->Password, $this->ConnectionOptions);
            $this->_Connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
            
            if($this->ConnectionOptions[1002])
               $this->Query($this->ConnectionOptions[1002]);
            
            // We only throw exceptions during connect
            $this->_Connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
         } catch (Exception $ex) {
            $Timeout = FALSE;
            if ($ex->getCode() == '2002' && preg_match('/Operation timed out/i', $ex->getMessage()))
               $Timeout = TRUE;
            if ($ex->getCode() == '2003' && preg_match("/Can't connect to MySQL/i", $ex->getMessage()))
               $Timeout = TRUE;
                    
            if ($Timeout)
               throw new Exception(ErrorMessage('Timeout while connecting to the database', $this->ClassName, 'Connection', $ex->getMessage()), 504);
            
            trigger_error(ErrorMessage('An error occurred while attempting to connect to the database', $this->ClassName, 'Connection', $ex->getMessage()), E_USER_ERROR);
         }
      }
      
      return $this->_Connection;
   }
1033160
public function getConnection()
    {
        if (empty($this->connection)) {

            if (empty($this->connectionConfig) || !is_array($this->connectionConfig))
                throw new DatabaseException("Connection config is empty or not an array.");

            $connCount = count($this->connectionConfig);
            for($i = 0; $i < $connCount; ++$i)
            {
                $connectionInfo = $this->connectionConfig[$i];

                if (empty($connectionInfo['port']))
                    $connectionInfo['port'] = 3306;

                $dsn = "mysql:dbname={$connectionInfo['database']};host={$connectionInfo['host']};port={$connectionInfo['port']}";
                if (!empty($connectionInfo['unix_socket']))
                    $dsn .= ';unix_socket='.$connectionInfo['unix_socket'];

                try {

                    $trx_attempt = 0;
                    while ($trx_attempt < $this->deadlockRetries) {

                        try {

                            $this->connection = new PDO($dsn, $connectionInfo['username'], $connectionInfo['password'], array(
                                PDO::ATTR_PERSISTENT => (!empty($connectionInfo['persistent'])?StringUtils::strToBool($connectionInfo['persistent']):false),
                                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                                PDO::ATTR_CASE => PDO::CASE_NATURAL,
                                PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
                                PDO::MYSQL_ATTR_DIRECT_QUERY => true,
                                PDO::ATTR_TIMEOUT => (!empty($connectionInfo['timeout'])?$connectionInfo['timeout']:30) ));


                            $this->connDebugString = $connectionInfo['host'].':'.$connectionInfo['database'];
                            $this->currentDBName = $connectionInfo['database'];

                            $this->Logger->debug(array(
                                'SQL'                    => 'CONNECTION - DB: '.$this->connDebugString,
                            ));

                            return $this->connection;

                        } catch (PDOException $pe) {
                            if ((strpos($pe->getMessage(), 'Too many connections') !== FALSE) && ++$trx_attempt < $this->deadlockRetries)
                            {
                                usleep( pow(2,$trx_attempt) * 100000 );
                                continue;
                            }

                            throw $pe;
                        }
                    }

                } catch(PDOException $pe)
                {

                    // if the last connection fails
                    if($i == ($connCount-1))
                        throw new SQLConnectionException($pe->getMessage());
                }
            }
        }

        return $this->connection;
    }
165894
public function connectToDB(){
        //if querybuilder is already connected there is no nedd to connect again
        if($this->queryBuilder->isConnected()) {
            return;
        }
        //check for database parameters
        if(empty($this->DBParameters)) {
            throw new \Exception('missing database parameters');
        }
        $this->queryBuilder->connect(
            $this->DBParameters['driver'],
            $this->DBParameters['host'],
            $this->DBParameters['database'],
            $this->DBParameters['username'],
            $this->DBParameters['password'],
            $this->DBParameters['charset'],
            $this->DBParameters['collation'],
            $this->DBParameters['options']
        );
    }
455779
private function connect()
    {
        try {
            $this->db = new \PDO(
                $this->dbOptions['dsn'],
                $this->dbOptions['username'],
                $this->dbOptions['password'],
                $this->dbOptions['driver_options']
            );

        } catch (\Exception $e) {
            //Change to true to debug database connection
            if ($this->dbOptions['debug']) {
                // For debug purpose, shows all connection details
                throw $e;
            } else {
                // Hide connection details.
                throw new \PDOException("Could not connect to database, hiding connection details.");
            }
        }
        $this->db->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
    }
1072417
public function getConnection()
    {
        if ($this->conn === false) {
            $this->conn = null;
            if ($this->url) {
                $buf = "Using database settings:\n"
                    . " URL: " . $this->url . "\n"
                    . ($this->userId ? " user: " . $this->userId . "\n" : "")
                . ($this->password ? " password: " . $this->password . "\n" : "");

                $this->log($buf, Project::MSG_VERBOSE);

                // Set user + password to null if they are empty strings
                if (!$this->userId) {
                    $this->userId = null;
                }
                if (!$this->password) {
                    $this->password = null;
                }
                try {
                    $this->conn = new PDO($this->url, $this->userId, $this->password);
                    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                } catch (PDOException $x) {
                    $this->log("Unable to create a PDO connection: " . $x->getMessage(), Project::MSG_WARN);
                }
            }
        }

        return $this->conn;
    }
829096
public static function conn()
    {
        // Auto connect using Jasny's Config class
        if (!isset(self::$connection)) {
            if (!class_exists('Jasny\Config') || !isset(\Jasny\Config::i()->db)) throw new DB_Exception("Unable to create DB connection: not configured");
            new static(\Jasny\Config::i()->db);
        }

        return self::$connection;
    }