Actually connect to database
486929
private function tryConnect(): void
    {
        $config = $this->getConfig();

        $pdoConfig = [
          PDO::ATTR_EMULATE_PREPARES => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_PERSISTENT => $config['persistent'] ?? true,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];

        if (isset($config['adapter_options'])) {
            foreach ($config['adapter_options'] as $key => $value) {
                $pdoConfig[$key] = $value;
            }
        }

        if (!isset($config['socket'])) {
            // not a socket
            $port = $config['port'] ?? 5432;

            $this->pdo = new PDO("pgsql:host={$config['host']};port={$port};dbname={$config['database']}", $config['username'], $config['password'], $pdoConfig);
        } else {
            // the case with unix_socket
            $this->pdo = new PDO("pgsql:dbname={$config['database']}", $config['username'], $config['password'], $pdoConfig);
        }

        if (isset($config['schema'])) {
            $schemaSql = 'SET search_path TO ' . $config['schema'];
            $this->pdo->exec($schemaSql);
            Log::sql($schemaSql);
        }
    }
550814
function connect( $server, $db, $user, $password, $socketPath, $charset = null, $port = false )
    {
        $connection = false;

        if ( $socketPath !== false )
        {
            ini_set( "mysqli.default_socket", $socketPath );
        }

        if ( $this->UsePersistentConnection == true )
        {
            // Only supported on PHP 5.3 (mysqlnd)
            if ( version_compare( PHP_VERSION, '5.3' ) > 0 )
                $server = 'p:' . $server;
            else
                eZDebug::writeWarning( 'mysqli only supports persistent connections when using php 5.3 and higher', __METHOD__ );
        }

        $oldHandling = eZDebug::setHandleType( eZDebug::HANDLE_EXCEPTION );
        eZDebug::accumulatorStart( 'mysqli_connection', 'mysqli_total', 'Database connection' );
        try {
            $connection = mysqli_connect( $server, $user, $password, null, (int)$port, $socketPath );
        } catch( ErrorException $e ) {}
        eZDebug::accumulatorStop( 'mysqli_connection' );
        eZDebug::setHandleType( $oldHandling );

        $maxAttempts = $this->connectRetryCount();
        $waitTime = $this->connectRetryWaitTime();
        $numAttempts = 1;
        while ( !$connection && $numAttempts <= $maxAttempts )
        {
            sleep( $waitTime );

            $oldHandling = eZDebug::setHandleType( eZDebug::HANDLE_EXCEPTION );
            eZDebug::accumulatorStart( 'mysqli_connection', 'mysqli_total', 'Database connection' );
            try {
                $connection = mysqli_connect( $server, $user, $password, null, (int)$port, $socketPath );
            } catch( ErrorException $e ) {}
            eZDebug::accumulatorStop( 'mysqli_connection' );
            eZDebug::setHandleType( $oldHandling );

            $numAttempts++;
        }
        $this->setError();

        $this->IsConnected = true;

        if ( !$connection )
        {
            eZDebug::writeError( "Connection error: Couldn't connect to database server. Please try again later or inform the system administrator.\n{$this->ErrorMessage}", __CLASS__ );
            $this->IsConnected = false;
            throw new eZDBNoConnectionException( $server, $this->ErrorMessage, $this->ErrorNumber );
        }

        if ( $this->IsConnected && $db != null )
        {
            $ret = mysqli_select_db( $connection, $db );
            if ( !$ret )
            {
                $this->setError( $connection );
                eZDebug::writeError( "Connection error: Couldn't select the database. Please try again later or inform the system administrator.\n{$this->ErrorMessage}", __CLASS__ );
                $this->IsConnected = false;
            }
        }

        if ( $charset !== null )
        {
            $originalCharset = $charset;
            $charset = eZCharsetInfo::realCharsetCode( $charset );
        }

        if ( $this->IsConnected and $charset !== null )
        {
            $status = mysqli_set_charset( $connection, eZMySQLCharset::mapTo( $charset ) );
            if ( !$status )
            {
                $this->setError();
                eZDebug::writeWarning( "Connection warning: " . mysqli_errno( $connection ) . ": " . mysqli_error( $connection ), "eZMySQLiDB" );
            }
        }

        return $connection;
    }
584025
def main():
    """"""
    logger.info('Waiting for database: `%s`', MYSQL_DB)

    connect_mysql(
        host=MYSQL_HOST, port=MYSQL_PORT,
        user=MYSQL_USER, password=MYSQL_PASSWORD,
        database=MYSQL_DB
    )

    logger.info('Database `%s` found', MYSQL_DB)
1110033
public static function connect() :void {

		// configure the database and get the dns
		$dsn = self::configureAndGetDSN();

		// try to connect
		self::$_handle = new \PDO(
			$dsn, 
			self::$_config['username'] ?: null, 
			self::$_config['password'] ?: null
		);

		// check if connection the connexion failed
		if(!self::$_handle) {
			// throw an exception if it failed
			Throw new Exception('Database::connect() : Failed to connect', 500);
		}

		// if a before statement has to be executed
		if(self::$_config['before']) {
			// execute the before statement
			self::$_handle->query(self::$_config['before']);
		}
	}
810609
def connect(self,
                engine: str = None,
                interface: str = None,
                host: str = None,
                port: int = None,
                database: str = None,
                driver: str = None,
                dsn: str = None,
                odbc_connection_string: str = None,
                user: str = None,
                password: str = None,
                autocommit: bool = True,
                charset: str = "utf8",
                use_unicode: bool = True) -> bool:
        

        # Catch all exceptions, so the error-catcher never shows a password.
        # Note also that higher-level things may catch exceptions, so use the
        # logger as well.
        try:
            return self._connect(
                engine=engine, interface=interface,
                host=host, port=port, database=database,
                driver=driver, dsn=dsn,
                odbc_connection_string=odbc_connection_string,
                user=user, password=password,
                autocommit=autocommit, charset=charset,
                use_unicode=use_unicode)
        except Exception as e:
            self.reraise_connection_exception(e)
1011185
public function connect() {
        $adapter = Zend_Db_Table::getDefaultAdapter();
        if (!$adapter) {
            Garp_Cli::errorOut('No database adapter found');
            return false;
        }
        $config = $adapter->getConfig();
        $params = array(
            '-u' . escapeshellarg($config['username']),
            '-p' . escapeshellarg($config['password']),
            '-h' . escapeshellarg($config['host']),
            ' ' . escapeshellarg($config['dbname'])
        );
        $cmd = 'mysql ' . implode(' ', $params);
        $process = proc_open($cmd, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
        $proc_status = proc_get_status($process);
        $exit_code = proc_close($process);
        return ($proc_status["running"] ? $exit_code : $proc_status["exitcode"] ) == 0;
    }
1207383
function open()
    {
        if (!$this->_opened) {
            /* Use the DSN and options to create a database connection. */
            $this->_db = &DB::connect($this->_dsn, $this->_options);
            if (DB::isError($this->_db)) {
                return false;
            }

            /* Create a prepared statement for repeated use in log(). */
            if (!$this->_prepareStatement()) {
                return false;
            }

            /* We now consider out connection open. */
            $this->_opened = true;
        }

        return $this->_opened;
    }
826338
def connect_engine(self):
        
        try:
            self.connection = self.engine.connect()
            return True
        except sa.exc.OperationalError as opex:
            LOG.fatal("Could not connect to the database. The error was: '%s'",
                      str(opex))
        return False
1055467
def _get_db_connect(dbSystem,db,user,password):
    
    if dbSystem=='SYBASE':
        import Sybase    
        try:
            dbh = Sybase.connect(dbSystem,
                                 user,
                                 password,
                                 database=db )
        except:
            dbh=None
    elif dbSystem=='MYSQL':
        import MySQLdb
        try:
            dbh = MySQLdb.connect(user=user,
                                  passwd=password,
                                  db=db ,
                                  host='gimli')
        except:
            dbh=None
            
    return dbh
1023745
final public function openConnection ()
	{
		$this->connection = mysqli_connect(
			getConstant('DB_HOST', TRUE),
			getConstant('DB_USERNAME', TRUE),
			getConstant('DB_PASSWORD', TRUE),
			getConstant('DB_NAME', TRUE)
		);
		$errorMessage 	= "Database connection failed: ".mysqli_connect_error();
		$errorMessage 	.= " (" .mysqli_connect_errno(). ")";
		if (!$this->connection) die($errorMessage);
	}
97459
def connectDb(engine   = dbeng,
              user     = dbuser,
              password = dbpwd,
              host     = dbhost,
              port     = dbport,
              database = dbname,
              params   = "?charset=utf8&use_unicode=1",
              echoopt  = False):
    
    return create_engine('%s://%s:%s@%s:%s/%s%s' % (engine, user, password, host, port, database, params), echo=echoopt)
96505
def _connect(self):
        
        self._close()
        self.conn = MySQLdb.Connect(host=self.hostname,
                                    port=self.port,
                                    user=self.username,
                                    passwd=self.password,
                                    db=self.database)
207251
final public function connect()
    {
        /* If an established connection is available, then there's
         * no need to connect and select the database.
         *
         * Depending on the database driver, conn_id can be either
         * boolean TRUE, a resource or an object.
         */
        if ($this->handle) {
            return;
        }

        //--------------------------------------------------------------------

        $this->connectTimeStart = microtime(true);

        // Connect to the database and set the connection ID
        $this->platformConnectHandler($this->config);

        // No connection resource? Check if there is a failover else throw an error
        if ( ! $this->handle) {
            // Check if there is a failover set
            if ( ! empty($this->config[ 'failover' ]) && is_array($this->config[ 'failover' ])) {
                // Go over all the failovers
                foreach ($this->config[ 'failover' ] as $failover) {

                    // Try to connect
                    $this->platformConnectHandler($failover = new Config($failover));

                    // If a connection is made break the foreach loop
                    if ($this->handle) {
                        $this->config = $failover;
                        break;
                    }
                }
            }

            // We still don't have a connection?
            if ( ! $this->handle) {
                throw new RuntimeException('DB_E_UNABLE_TO_CONNECT', 0, [$this->platform]);
            }
        }

        $this->connectTimeDuration = microtime(true) - $this->connectTimeStart;
    }
1121273
def connection(connection, without_connection_test):
    """"""
    database.set_connection(connection=connection)

    if not without_connection_test:
        test_connection(connection)
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());
        }
    }
1165236
def _connect(self):
        """"""
        if not self._db:
            import boto
            sdb = boto.connect_sdb()
            if not self.domain_name:
                self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default"))
            try:
                self._db = sdb.get_domain(self.domain_name)
            except SDBResponseError, e:
                if e.status == 400:
                    self._db = sdb.create_domain(self.domain_name)
                else:
                    raise
        return self._db
1251048
protected function _connect(){

		$this->_connection = @mysqli_connect(
			$this->_server, $this->_username, $this->_password);

		if(!@mysqli_select_db($this->_connection, $this->_database)){

			// Connection established, but unable to access the database

			if(!$this->_connection){

				throw new ConnectionException('Could not open the
					requested database');
			}
			else{

				throw new ConnectionException('Could not connect to the
					MySQL server');
			}
		}
	}