Try connecting to the database
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;
            }
        }
884353
def connect(self):
        """"""
        self._client = self._create_client()
        self._db = getattr(self._client, self._db_name)
        self._generic_dao = GenericDAO(self._client, self._db_name)
1197255
async def connect(self) -> Connection:
        
        if self._conn is None:
            self._conn = await r.connect(host=self._host,
                                         port=self._port,
                                         db=self._db,
                                         auth_key=self._auth_key,
                                         user=self._user,
                                         password=self._password,
                                         timeout=self._timeout,
                                         ssl=self._ssl,
                                         io_loop=self._loop)
        return self._conn
672398
public function connect() : void
    {
        $this->logger->info('Connecting to LDAP');
        // Connect to the LDAP server
        $handle = ldap_connect($this->configuration['server'], $this->configuration['port']);

        if (is_resource($handle)) {
            ldap_set_option($handle, LDAP_OPT_PROTOCOL_VERSION, 3);
            ldap_set_option($handle, LDAP_OPT_REFERRALS, 0);
            $this->logger->info('Connected to LDAP');
            $this->handle = $handle;
        } else {
            throw new DatabaseConnectionException('Unable to connect to LDAP');
        }
        $this->logger->debug('Connecting to database engine.');
        $this->bindToServer();
        $this->logger->debug('Connected to database engine.');
        $this->is_connected = true;
    }
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");
    }
1258683
public function connect()
    {
        $arrParams = [
            'mysql:host='.$this->host,
            'dbname='.$this->database,
            'charset='.$this->charset,
        ];
        
        $this->db = PdoSingleton::getInstance()->getConnection($arrParams, $this->username, $this->password);
    }
307554
public function connect()
    {
        $config = $this->getConfig();
        if(isset($config['database']['database'])) {
            $conn = $this->instanceConnector();
            $host = $config['database']['hostname'];
            $user = $config['database']['username'];
            $pass = $config['database']['password'];
            if ($conn->connect($host, $user, $pass)) {
                $this->connection = $conn;
                $this->createCache();
                return true;
            }
            $err = $conn->getLastError();
            throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
                        $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
        }

        return false;

//        if (!$this->connection) {
//
//            if ($conn->connect()
//            ) {
//                if ($conn->select_database($config['database']['database'])) {
//                    $this->connection = $conn;
//                    self::$selected = true;
//                    $this->createCache();
////
////                    if (!defined("GL_INSTALL") || !GL_INSTALL) {
////                        $this->checkDatabaseStructure();
////                    }
//                    return true;
//                }
//                return false;
//            } else {
//                $err =$conn->getLastError();
//                throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
//                    $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
//            }
//        }
//        return true;
    }
210854
public function connectDb()
    {     
        if ($this->_connected) return;
		
		if (function_exists('mysql_connect')) {
			try {
				mysql_connect($this->getVar('dbhost'),$this->getVar('dbuser'),$this->getVar('dbpass'));
				mysql_select_db($this->getVar('dbname'));
				mysql_query('SET NAMES utf8');
			} catch (\Exception $e) {
				throw new \Exception($e->getMessage());
			}
		}		
        
        $connectionParams = array(
            'dbname'       => $this->getVar('dbname'),
            'user'         => $this->getVar('dbuser'),
            'password'     => $this->getVar('dbpass'),
            'host'         => $this->getVar('dbhost'),
            'driver'       => $this->getVar('dbdriver')?$this->getVar('dbdriver'):'pdo_mysql',
			'wrapperClass' => 'Cetera\Database\Connection',
        );
 
        $this->_dbConnection = \Doctrine\DBAL\DriverManager::getConnection( 
            $connectionParams, 
            new \Doctrine\DBAL\Configuration()
        );        

		$charset = $this->getVar('dbcharset');
		if (!$charset) $charset = 'utf8';
            
        $this->_dbConnection->executeQuery('SET CHARACTER SET '.$charset);
        $this->_dbConnection->executeQuery('SET names '.$charset);
            
        $this->_connected = true; 
            
    }
1028565
public function connect() {
        if (!class_exists('SQLite3')) throw new RuntimeException('Undefined class \SQLite3, sqlite3 extension is not available');

        try {                                                                   // available flags:
            $flags  = SQLITE3_OPEN_READWRITE;                                   // SQLITE3_OPEN_CREATE
            $sqlite = new \SQLite3($this->file, $flags);                        // SQLITE3_OPEN_READONLY
        }                                                                       // SQLITE3_OPEN_READWRITE
        catch (\Exception $ex) {
            if (!$ex instanceof IRosasurferException)
                $ex = new DatabaseException($ex->getMessage(), $ex->getCode(), $ex);
            $file = $this->file;
            $what = $where = null;
            if (file_exists($file)) {
                $what = 'open';
                if (is_dir($file=realpath($file)))
                    $where = ' (directory)';
            }
            else {
                $what = ($flags & SQLITE3_OPEN_CREATE) ? 'create':'find';
                isRelativePath($file) && $where=' in "'.getcwd().'"';
            }
            throw $ex->addMessage('Cannot '.$what.' database file "'.$file.'"'.$where);
        }

        $this->sqlite = $sqlite;
        $this->setConnectionOptions();
        return $this;
    }
797371
def connect(
    database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any
) -> Connection:
    """"""
    if loop is None:
        loop = asyncio.get_event_loop()

    def connector() -> sqlite3.Connection:
        if isinstance(database, str):
            loc = database
        elif isinstance(database, bytes):
            loc = database.decode("utf-8")
        else:
            loc = str(database)

        return sqlite3.connect(loc, **kwargs)

    return Connection(connector, loop)
1251783
public function check_database()
    {

        $this->line(' * Checking Database');
        $this->table(['Setting', 'Value'], [
            ['Connection', env('DB_CONNECTION')],
            ['Host', env('DB_HOST')],
            ['Database', env('DB_DATABASE')],
            ['Username', env('DB_USERNAME')],
            ['Password', str_repeat('*', strlen(env('DB_PASSWORD')))],
        ]);

        try {

            $this->info('Connection OK to database: ' .
                DB::connection()->getDatabaseName());

        } catch (Exception $e) {

            $this->error('Unable to connect to database server: ' . $e->getMessage());
        }
    }
244508
public void open() throws SQLException, ClassNotFoundException {
        logger.info("Using database driver: " + jdbcDriver);
        Class.forName(jdbcDriver);
        logger.info("Using database.url: " + jdbcURL);
        // connect login/pass
        con = DriverManager.getConnection(jdbcURL, user, password);
        // Exception will be thrown if something went wrong
        connected = true;
    }
1283477
def _open(self):
        
        try:
            self.db = connect(
                host=self.settings.host,
                port=self.settings.port,
                user=coalesce(self.settings.username, self.settings.user),
                passwd=coalesce(self.settings.password, self.settings.passwd),
                db=coalesce(self.settings.schema, self.settings.db),
                read_timeout=coalesce(self.settings.read_timeout, (EXECUTE_TIMEOUT / 1000) - 10 if EXECUTE_TIMEOUT else None, 5*60),
                charset=u"utf8",
                use_unicode=True,
                ssl=coalesce(self.settings.ssl, None),
                cursorclass=cursors.SSCursor
            )
        except Exception as e:
            if self.settings.host.find("://") == -1:
                Log.error(
                    u"Failure to connect to {{host}}:{{port}}",
                    host=self.settings.host,
                    port=self.settings.port,
                    cause=e
                )
            else:
                Log.error(u"Failure to connect.  PROTOCOL PREFIX IS PROBABLY BAD", e)
        self.cursor = None
        self.partial_rollback = False
        self.transaction_level = 0
        self.backlog = []  # accumulate the write commands so they are sent at once
        if self.readonly:
            self.begin()
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);
    }
1164372
def connect_to_database(db_settings, force = false)
      # only setup database connection once
      if force
        ActiveRecord::Base.establish_connection(db_settings)
      else
        begin
          ActiveRecord::Base.connection
        rescue => e
          require 'pp'
          pp db_settings
          puts "failed to connect: #{e}"
          ActiveRecord::Base.establish_connection(db_settings)
        end
      end
    end
54374
function _tryReconnect(dbInfo) {
    _deferReadiness(dbInfo);

    var dbContext = dbContexts[dbInfo.name];
    var forages = dbContext.forages;

    for (var i = 0; i < forages.length; i++) {
        var forage = forages[i];
        if (forage._dbInfo.db) {
            forage._dbInfo.db.close();
            forage._dbInfo.db = null;
        }
    }
    dbInfo.db = null;

    return _getOriginalConnection(dbInfo).then(function (db) {
        dbInfo.db = db;
        if (_isUpgradeNeeded(dbInfo)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
        }
        return db;
    }).then(function (db) {
        // store the latest db reference
        // in case the db was upgraded
        dbInfo.db = dbContext.db = db;
        for (var i = 0; i < forages.length; i++) {
            forages[i]._dbInfo.db = db;
        }
    })["catch"](function (err) {
        _rejectReadiness(dbInfo, err);
        throw err;
    });
}
1200074
public function connect()
  {
    try {
      $this->cnx = new SQLitePDO($this->fileName);
      $this->cnx->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      return true;
    } catch (\Exception $e) {
      return false;
    }
  }