Connect to MongoDB Host.

@throws DBException
162978
public void connect() throws DBException {
        try {
            LOGGER.debug("Initializing MongoDB client");
            mongoClient = new MongoClient(this.host, this.port);
        } catch (UnknownHostException e) {
            throw new DBException(e.toString());

        }
    }
771749
public function connect() {
        $dbConfig = $this->getDbConfig();
        $this->setDbConfig($dbConfig);
        $this->setORM($dbConfig);
        HookManager::call('dbConnect', self::$dbConnections, self::$ormPath);
    }
725132
public function connectToDb()
    {
        $this->con = new PDO("mysql:host=$this->host", $this->username, $this->password);
        $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->con->query("CREATE DATABASE IF NOT EXISTS " . $this->dbName);
        $this->con->query("USE " . $this->dbName);
    }
1142300
public function prepare(string $confKey, string $db, string $collection)
    {
        $this->profileName = 'mongo.' . $db . '.';
        $this->config = getInstance()->config['mongodb'] ?? [];
        if (!isset($this->config[$confKey])) {
            throw new \MongoConnectionException('No such a MongoDB config ' . $confKey);
        }
        $conf = $this->config[$confKey];
        $this->mongoClient = new \MongoClient($conf['server'], $conf['options'], $conf['driverOptions']);
        $db && ($this->mongoDb = $this->mongoClient->selectDB($db));
        $collection && ($this->mongoCollection = $this->mongoDb->selectCollection($collection));
    }
292094
function(callback) {

  log('Connecting...');
  MongoClient.connect(dbUrl, dbOptions, function(err, dbConn) {
    
    if(err) {
      log('Cannot connect: ' + err);
      callback(err);
      return;
    } 
    
    log('Connected!');
    isConnected = true;
    db = dbConn;

    // http://stackoverflow.com/a/18715857/446681
    db.on('close', function() {
      log('Connection was closed!!!');
      isConnected = false;
    });

    log('Executing...');
    callback(null, db);
  
  });

}
822838
def connect(self):
        
        mongodb_args = {
            'host': self.host,
            'port': self.port,
            'username': self._username,
            'password': self._password,
            'authSource': self._auth_source,
            'serverSelectionTimeoutMS': self._connect_timeout
        }

        if self._auth_mechanism is not None:
            mongodb_args['authMechanism'] = self._auth_mechanism

        self._client = MongoClient(**mongodb_args)

        if self._handle_reconnect:
            self._client = MongoClientProxy(self._client)
1013428
public function connect() {
    // Check that the SQLite3 extension is installed.
    if (!class_exists('SQLite3')) {
      throw new Exceptions\UnableToConnectException(
          'SQLite3 PHP extension is not available. It probably has not '.
          'been installed. Please install and configure it in order to use '.
          'SQLite3.'
      );
    }
    $filename = $this->config['SQLite3']['filename'];
    $busyTimeout = $this->config['SQLite3']['busy_timeout'];
    $openFlags = $this->config['SQLite3']['open_flags'];
    $encryptionKey = $this->config['SQLite3']['encryption_key'];
    // Connecting
    if (!$this->connected) {
      $this->link = new SQLite3($filename, $openFlags, $encryptionKey);
      if ($this->link) {
        $this->connected = true;
        $this->link->busyTimeout($busyTimeout);
        // Set database and connection options.
        $this->link->exec("PRAGMA encoding = \"UTF-8\";");
        $this->link->exec("PRAGMA foreign_keys = 1;");
        $this->link->exec("PRAGMA case_sensitive_like = 1;");
        // Create the preg_match and regexp functions.
        // TODO(hperrin): Add more of these functions to get rid of post-query checks.
        $this->link->createFunction('preg_match', 'preg_match', 2, SQLITE3_DETERMINISTIC);
        $this->link->createFunction('regexp', function ($pattern, $subject) {
          return !!$this->posixRegexMatch($pattern, $subject);
        }, 2, SQLITE3_DETERMINISTIC);
      } else {
        $this->connected = false;
        if ($filename === ':memory:') {
          throw new Exceptions\NotConfiguredException();
        } else {
          throw new Exceptions\UnableToConnectException('Could not connect.');
        }
      }
    }
    return $this->connected;
  }
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;
            }
        }
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;
    }
949809
protected function connectDblib()
    {
        if (!class_exists('PDO') || !in_array('dblib', \PDO::getAvailableDrivers(), true)) {
            // @codeCoverageIgnoreStart
            throw new \RuntimeException('You need to enable the PDO_Dblib extension for Phinx to run properly.');
            // @codeCoverageIgnoreEnd
        }

        $options = $this->getOptions();

        // if port is specified use it, otherwise use the SqlServer default
        if (empty($options['port'])) {
            $dsn = 'dblib:host=' . $options['host'] . ';dbname=' . $options['name'];
        } else {
            $dsn = 'dblib:host=' . $options['host'] . ':' . $options['port'] . ';dbname=' . $options['name'];
        }

        $driverOptions = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];

        try {
            $db = new \PDO($dsn, $options['user'], $options['pass'], $driverOptions);
        } catch (\PDOException $exception) {
            throw new \InvalidArgumentException(sprintf(
                'There was a problem connecting to the database: %s',
                $exception->getMessage()
            ));
        }

        $this->setConnection($db);
    }
399977
protected function opendb() {
    // Only do one open
    
    if($this->db) {
      return $this->db;
    }

    $db = @mysql_connect($this->host, $this->user, $this->password, true);

    if(!$db) {
      throw new SqlException(__METHOD__ . ": Can't connect to database", $this);
    }

    $this->db = $db; // set this right away so if we get an error below $this->db is valid

    if(!@mysql_select_db($this->database, $db)) {
      throw new SqlException(__METHOD__ . " Can't select database", $this);
    }
    return $db;
  }
1176307
void connectDBConn(DBConn dbConn) throws DBNotAvailableException, RuntimeException {
        // If we're using failover hosts, see if it's time to try primary hosts again.
        if (m_bUseSecondaryHosts &&
            (System.currentTimeMillis() - m_lastPrimaryHostCheckTimeMillis) > getParamInt("primary_host_recheck_millis", 60000)) {
            m_bUseSecondaryHosts = false;
        }
        
        // Try all primary hosts first if possible.
        DBNotAvailableException lastException = null;
        if (!m_bUseSecondaryHosts) {
            String[] dbHosts = getParamString("dbhost").split(",");
            for (int attempt = 1; !dbConn.isOpen() && attempt <= dbHosts.length; attempt++) {
                try {
                    dbConn.connect(chooseHost(dbHosts));
                } catch (DBNotAvailableException ex) {
                    lastException = ex;
                } catch (RuntimeException ex) {
                    throw ex;   // bad keyspace; abort connection attempts
                }
            }
            m_lastPrimaryHostCheckTimeMillis = System.currentTimeMillis();
        }
        
        // Try secondary hosts if needed and if configured.
        if (!dbConn.isOpen() && !Utils.isEmpty(getParamString("secondary_dbhost"))) {
            if (!m_bUseSecondaryHosts) {
                m_logger.info("All connections to 'dbhost' failed; trying 'secondary_dbhost'");
            }
            String[] dbHosts = getParamString("secondary_dbhost").split(",");
            for (int attempt = 1; !dbConn.isOpen() && attempt <= dbHosts.length; attempt++) {
                try {
                    dbConn.connect(chooseHost(dbHosts));
                } catch (DBNotAvailableException e) {
                    lastException = e;
                } catch (RuntimeException ex) {
                    throw ex;   // bad keyspace; abort connection attempts
                }
            }
            if (dbConn.isOpen()) {
                m_bUseSecondaryHosts = true; // stick with secondary hosts for now.
            }
        }
        
        if (!dbConn.isOpen()) {
            m_logger.error("All Thrift connection attempts failed.", lastException);
            throw lastException;
        }
    }
736634
@Override
    public synchronized Mongo connect() {
        if (m == null) {
            final String dbName = mongoClientURI.getDatabase();
            if (isNullOrEmpty(dbName)) {
                LOG.error("The MongoDB database name must not be null or empty (mongodb_uri was: {})", mongoClientURI);
                throw new RuntimeException("MongoDB database name is missing.");
            }

            m = new MongoClient(mongoClientURI);
            db = m.getDB(dbName);
            db.setWriteConcern(WriteConcern.ACKNOWLEDGED);

            mongoDatabase = m.getDatabase(dbName).withWriteConcern(WriteConcern.ACKNOWLEDGED);
        }

        try {
            db.command("{ ping: 1 }");
        } catch (MongoCommandException e) {
            if (e.getCode() == 18) {
                throw new MongoException("Couldn't connect to MongoDB. Please check the authentication credentials.", e);
            } else {
                throw new MongoException("Couldn't connect to MongoDB: " + e.getMessage(), e);
            }
        }

        final Version mongoVersion = getMongoVersion(m.getDB("admin"));
        if (mongoVersion != null && mongoVersion.lessThan(MINIMUM_MONGODB_VERSION)) {
            LOG.warn("You're running MongoDB {} but Graylog requires at least MongoDB {}. Please upgrade.",
                    mongoVersion, MINIMUM_MONGODB_VERSION);
        }

        return m;
    }
963566
public function _connect()
    {
        $siteINI = eZINI::instance( 'site.ini' );
        // DB Connection setup
        // This part is not actually required since _connect will only be called
        // once, but it is useful to run the unit tests. So be it.
        // @todo refactor this using eZINI::setVariable in unit tests
        if ( self::$dbparams === null )
        {
            $fileINI = eZINI::instance( 'file.ini' );

            self::$dbparams = array();
            self::$dbparams['host']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBHost' );
            self::$dbparams['port']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPort' );
            self::$dbparams['socket']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBSocket' );
            self::$dbparams['dbname']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBName' );
            self::$dbparams['user']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBUser' );
            self::$dbparams['pass']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPassword' );

            self::$dbparams['max_connect_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBConnectRetries' );
            self::$dbparams['max_execute_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBExecuteRetries' );

            self::$dbparams['sql_output'] = $siteINI->variable( 'DatabaseSettings', 'SQLOutput' ) == 'enabled';

            self::$dbparams['cache_generation_timeout'] = $siteINI->variable( 'ContentSettings', 'CacheGenerationTimeout' );
        }


        $connectString = sprintf( 'pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s',
            self::$dbparams['host'],
            self::$dbparams['port'],
            self::$dbparams['dbname'],
            self::$dbparams['user'],
            self::$dbparams['pass']
        );
        $tries = 0;
        while ( $tries < self::$dbparams['max_connect_tries'] )
        {
            try {
                $this->db = new PDO( $connectString, self::$dbparams['user'], self::$dbparams['pass'] );
            } catch ( PDOException $e ) {
                eZDebug::writeError( $e->getMessage() );
                ++$tries;
                continue;
            }
            break;
        }
        if ( !( $this->db instanceof PDO ) )
        {
            $this->_die( "Unable to connect to storage server" );
            throw new eZClusterHandlerDBNoConnectionException( $connectString, self::$dbparams['user'], self::$dbparams['pass'] );
        }


        if ( !$this->db )
            throw new eZClusterHandlerDBNoConnectionException( $connectString, self::$dbparams['user'], self::$dbparams['pass'] );

        $this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $this->db->exec( "SET NAMES 'utf8'" );


        // DFS setup
        if ( $this->dfsbackend === null )
            $this->dfsbackend = new eZDFSFileHandlerDFSBackend();
    }
905067
private function databaseConnect()
    {
        $dsn = 'mysql:host='.$this->db['host'].';port='.$this->db['port'].';dbname='.$this->db['name'];

        $options = array(
            \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            \PDO::ATTR_PERSISTENT         => true,
            \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION
        );

        // Create a new PDO instance
        try
        {
            $this->dbh = new \PDO($dsn, $this->db['user'], $this->db['password'], $options);
        }
        // Catch any errors
        catch (\PDOException $e)
        {
            exit($e->getMessage());
        }
    }
394369
public static function connect($dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [], $cache = false) {
		self::$db = new Database ( $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache );
		try {
			self::$db->connect ();
		} catch ( \Exception $e ) {
			Logger::error ( "DAO", $e->getMessage () );
			throw new DAOException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
		}
	}
114244
public synchronized void connect_db() {

	//
	// Try to connect to the database
	//

	if (_daemon == true) {
	    boolean connected = false;
	    while (connected == false) {
		try {
		    db = ApiUtil.get_db_obj();
		    if (db == null) {
			Util.out4.println("Can't contact db server, will try later");
			try {
			    wait(_sleep_between_connect * 1000);
			} catch (final InterruptedException ex) {
			}
		    } else {
			connected = true;
		    }
		} catch (final Exception e) {
		    Util.out4.println("Can't contact db server, will try later");
		    try {
			wait(_sleep_between_connect * 1000);
		    } catch (final InterruptedException ex) {
		    }
		}
	    }
	} else {
	    try {
		db = ApiUtil.get_db_obj();
		if (db == null) {
		    System.err.println("Can't build connection to TANGO database server, exiting");
		    System.err.println("DB server host = " + db_host);
		    System.exit(-1);
		}

	    } catch (final Exception ex) {
		System.err.println("Can't build connection to TANGO database server, exiting");
		System.err.println("DB server host = " + db_host);
		System.exit(-1);
	    }
	}
	Util.out4.println("Connected to database");
    }