Connect to a database by using constructor params

@return PDO

@throws \Exception
544817
public function connect()
    {
        $dsnString = "{$this->dbDriver}:host={$this->dbHostname};dbname={$this->dbName};";
        $dsnString .= "charset={$this->dbCharset}";
        /*
         * Try to connect to database
         */
        try {
            $this->dbConnection = new \PDO(
                $dsnString,
                "{$this->dbUsername}",
                "{$this->dbPassword}",
                $this->driverOptions
            );
        } catch (\PDOException $ex) {
            // Error during database connection, check params.
            throw new \InvalidArgumentException(
                __METHOD__.': '.$ex->getMessage()
            );
        }

        return $this->dbConnection;
    }
874086
public function getConnection() {
        if (is_null($this->conn) || !($this->conn)) {
            $dsn = 'dblib:host=' . $this->host . ':1433;dbname=' . $this->db . ';charset=utf8';
            $this->conn = new \PDO($dsn, $this->user, $this->pass);

            if (is_bool($this->conn)) {
                throw new \Exception('unable to connect to db with provided credentials');
            }
        }

        return $this->conn;
    }
520859
protected function _connect()
    {
        // if we already have a PDO object, no need to re-connect.
        if ($this->_connection) {
            return;
        }

        // get the dsn first, because some adapters alter the $_pdoType
        $dsn = $this->_dsn();

        // check for PDO extension
        if (!extension_loaded('pdo')) {
            /**
             * @see Zend_Db_Adapter_Exception
             */
            // require_once 'Zend/Db/Adapter/Exception.php';
            throw new Zend_Db_Adapter_Exception('The PDO extension is required for this adapter but the extension is not loaded');
        }

        // check the PDO driver is available
        if (!in_array($this->_pdoType, PDO::getAvailableDrivers())) {
            /**
             * @see Zend_Db_Adapter_Exception
             */
            // require_once 'Zend/Db/Adapter/Exception.php';
            throw new Zend_Db_Adapter_Exception('The ' . $this->_pdoType . ' driver is not currently installed');
        }

        // create PDO connection
        $q = $this->_profiler->queryStart('connect', Zend_Db_Profiler::CONNECT);

        // add the persistence flag if we find it in our config array
        if (isset($this->_config['persistent']) && ($this->_config['persistent'] == true)) {
            $this->_config['driver_options'][PDO::ATTR_PERSISTENT] = true;
        }

        try {
            $this->_connection = new PDO(
                $dsn,
                $this->_config['username'],
                $this->_config['password'],
                $this->_config['driver_options']
            );

            $this->_profiler->queryEnd($q);

            // set the PDO connection to perform case-folding on array keys, or not
            $this->_connection->setAttribute(PDO::ATTR_CASE, $this->_caseFolding);

            // always use exceptions.
            $this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (PDOException $e) {
            /**
             * @see Zend_Db_Adapter_Exception
             */
            // require_once 'Zend/Db/Adapter/Exception.php';
            throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
        }

    }
704519
protected function dbConnect() {
		try {
			$pdo = new PDO('mysql:host=' . conf::$db['host'] . ';dbname=' . conf::$db['name'], conf::$db['user'], conf::$db['pass']);
    		$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			return $pdo;
		} catch(PDOException $e) {
			return false;
		}
	}
955788
private function connection() {
      $this->apply_config_db();
      try {
         if ( @$_ENV["daniia_connection"] && !$this->id_conn ) {
            $this->id_conn = $_ENV["daniia_connection"];
         }
         elseif ( !$this->id_conn ) {
            $this->id_conn = new \PDO($this->dsn, $this->user, $this->pass);
         }
      } catch (\PDOException $e) {
         die("Error: " . $e->getMessage() . "<br/>");
      }

      $this->get_instance();
      return $this;
   }
403182
public function connect(\stdClass $params): QueryBuilderInterface
	{
		list($dsn, $dbtype, $params, $options) = $this->parseParams($params);

		$dbtype = ucfirst($dbtype);
		$driver = "\\Query\\Drivers\\{$dbtype}\\Driver";

		// Create the database connection
		$db =  ! empty($params->user)
			? new $driver($dsn, $params->user, $params->pass, $options)
			: new $driver($dsn, '', '', $options);

		// Set the table prefix, if it exists
		if (isset($params->prefix))
		{
			$db->setTablePrefix($params->prefix);
		}

		// Create Query Builder object
		$conn = new QueryBuilder($db, new QueryParser($db));


		// Save it for later
		if (isset($params->alias))
		{
			$this->connections[$params->alias] = $conn;
		}
		else
		{
			$this->connections[] = $conn;
		}

		return $conn;
	}
698573
public function connect()
    {
        $dsn = "sqlite:{$this->_file}";
        try {
            $class = $this->_handlerClass;
            $this->_handler = new $class($dsn);
            $this->_handler->setAttribute(
                PDO::ATTR_ERRMODE,
                PDO::ERRMODE_EXCEPTION
            );
            $this->_connected = true;
        } catch (\Exception $exp) {
            throw new ServiceException(
                "An error occurred when trying to connect to database " .
                "service. Error: {$exp->getMessage()}"
            );
        }
        return $this;
    }
1228512
public function connect()
    {
        return new PDO($this->getDsn(), $this->config['username'], $this->config['password'], $this->getOptions());
    }
695057
public function getPDO(): PDO
    {
        if ($this->pdo == null) {
            $this->pdo = new PDO($this->getDSN(), $this->username, $this->password, $this->options);

            foreach ($this->commands as $command) {
                $this->command($command['sql'], $command['params']);
            }
        }

        return $this->pdo;
    }
1029994
public function connect()
    {
        // Lookup Adapter-Specific Connection Properties
        $strServer = $this->Server;
        $strName = $this->Database;
        $strUsername = $this->Username;
        $strPassword = $this->Password;
        $strPort = $this->Port;

        // Connect to the Database Server
        $this->objPgSql = pg_connect(sprintf('host=%s dbname=%s user=%s password=%s port=%s', $strServer, $strName,
            $strUsername, $strPassword, $strPort));

        if (!$this->objPgSql) {
            throw new \Exception("Unable to connect to Database", -1, null);
        }

        // Update Connected Flag
        $this->blnConnectedFlag = true;
    }
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;
    }
1087612
public final function open() : Connection
   {

      if ( $this->isOpen() )
      {
         return $this;
      }

      $attrSupport       = $this->_driver->getAttributeSupport();
      $definedAttributes = $this->_driver->getDefinedAttributes();


      $dsn  = $this->_driver->getType() . ':';
      $dsnC = 0;
      $user = null;
      $pass = null;
      $sql  = [];
      $opts = [];

      foreach( $definedAttributes as $attrName => $attrValue )
      {

         $attrDesc = $attrSupport->get( $attrName );

         if ( null === $attrDesc ) { continue; }

         switch ( $attrDesc->getType() )
         {

            case Type::DSN_PART:
               if ( $dsnC < 1 )
               {
                  $dsnC++;
               }
               else
               {
                  $dsn .= $attrSupport->getDSNAttributeSeparator();
               }
               if ( $attrDesc->useNameInDSN() )
               {
                  $dsn .= $attrName . $attrSupport->getDSNKeyValueSeparator();
               }
               $dsn .= $attrValue;
               break;

            case Type::USERNAME_PARAM:
               $user = $attrValue;
               break;

            case Type::PASSWORD_PARAM:
               $pass = $attrValue;
               break;

            case Type::OPTION_PARAM:
               $opts[ $attrName ] = $attrValue;
               break;

            #case Type::INIT_SQL:
            default:
               if ( 'charset' === $attrName )
               {
                  $sql[] = 'SET NAMES ' . $attrValue;
                  break;
               }
               $sql[] = $attrValue;
               break;

         }

      }

      try
      {
         if ( ! isset( $opts[ \PDO::ATTR_ERRMODE ] ) )
         {
            $opts[ \PDO::ATTR_ERRMODE ] = \PDO::ERRMODE_EXCEPTION;
         }
         if ( $this->_driver->getType() === 'sqlite' || ( null === $user && null === $pass ) )
         {
            $this->_pdo = new \PDO( $dsn, null, null, $opts );
         }
         else
         {
            $this->_pdo = new \PDO( $dsn, $user, $pass, $opts );
         }
      }
      catch ( \Throwable $ex )
      {
         throw new ConnectionException( $this->_driver, 'Connection init fails!', 256, $ex );
      }

      if ( 0 < \count( $sql ) )
      {

         foreach ( $sql as $sqlString )
         {
            try { $this->_pdo->exec( $sqlString ); }
            catch ( \Throwable $ex )
            {
               throw new QueryException(
                  $this->_driver, $sqlString, [], 'Can not call the initial query!', 256, $ex
               );
            }
         }

      }

      return $this;

   }
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);
    }
341842
protected function connectDatabase()
    {
        if (!$this->databaseConfig) {
            return null;
        }

        $this->databaseConnection = ConnectionManager::create($this->databaseConfig);
    }
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);
    }
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());
        }
    }
150770
public static function connectDb() {
        if 
            (!isset(self::$dbLink)) {
            $dbParams = self::getDatabaseParameters();
            self::validateDbParameters($dbParams);
            $dbParamsSan = self::sanitizeDbParameters($dbParams);
            $config = new Configuration();
            self::$dbLink = DriverManager::getConnection($dbParamsSan, $config);
        }
        
        return self::$dbLink;
    }