Connect to PostgreSQL, either by reusing a connection from the pool
        if possible, or by creating the new connection.

        :rtype: psycopg2.extensions.connection
        :raises: pool.NoIdleConnectionsError
431599
def _connect(self):
        
        future = concurrent.Future()

        # Attempt to get a cached connection from the connection pool
        try:
            connection = self._pool_manager.get(self.pid, self)
            self._connections[connection.fileno()] = connection
            future.set_result(connection)

            # Add the connection to the IOLoop
            self._ioloop.add_handler(connection.fileno(),
                                     self._on_io_events,
                                     ioloop.IOLoop.WRITE)
        except pool.NoIdleConnectionsError:
            self._create_connection(future)

        return future
724043
def get_pooled_pg_core(connection_string, pool_size=None, *, cursor_factory=None,
                       edit_connection=None, threaded=True):
  
  from psycopg2.extras import NamedTupleCursor
  from psycopg2.pool import ThreadedConnectionPool as TPool, SimpleConnectionPool as SPool
  if not pool_size:
    pool_size = (5, 10)
  if threaded:
    pool = TPool(pool_size[0], pool_size[1], connection_string)
  else:
    pool = SPool(pool_size[0], pool_size[1], connection_string)

  def opener():
    """Gets a PostgreSQL connection from the scope-captured connection pool."""
    cn = pool.getconn()
    cn.cursor_factory = cursor_factory or NamedTupleCursor
    if edit_connection:
      edit_connection(cn)
    return cn

  def closer(connection):
    """Returns a connection to the scope-captured connection pool."""
    pool.putconn(connection)

  return InjectedDataAccessCore(
    opener,
    closer,
    ("%({0})s", "%s", "{0}::{1}"),
    empty_params=None,
    supports_timezones=True,
    supports_returning_syntax=True,
    get_autocommit=get_pg_autocommit,
    set_autocommit=set_pg_autocommit)
1353152
def create_connection(self):
        
        attempts = 0
        while True:
            attempts += 1
            try:
                self.connection = Connection('127.0.0.1', 'guest', 'guest')
                break
            except amqpstorm.AMQPError as why:
                LOGGER.exception(why)
                if self.max_retries and attempts > self.max_retries:
                    break
                time.sleep(min(attempts * 2, 30))
            except KeyboardInterrupt:
                break
408400
def connect(self, *args, auto_reconnect=False, **kwargs):
        
        connection_info = {
            'auto_reconnect': auto_reconnect,
            'args': args,
            'kwargs': kwargs,
        }
        self.connect_info['connection'] = connection_info

        # confirm we have user info set
        if 'user' not in self.connect_info:
            raise Exception('`set_user_info` must be called before connecting to server.')

        # create connection and run
        connection = loop.create_connection(lambda: self,
                                            *args, **kwargs)
        asyncio.Task(connection)
86149
def connect(self):
        
        if self._sock:
            return
        try:
            sock = self._connect()
        except socket.error:
            e = sys.exc_info()[1]
            raise ConnectionError(self._error_message(e))

        self._sock = sock
        try:
            self.on_connect()
        except SSDBError:
            # clean up after any error in on_connect
            self.disconnect()
            raise

        # run any user callbacks. right now the only internal callback
        # is for pubsub channel/pattern resubscription
        for callback in self._connect_callbacks:
            callback(self)
1311128
def _connect(self, database=None):
        
        conn_args = {
            'host': self.config['host'],
            'user': self.config['user'],
            'password': self.config['password'],
            'port': self.config['port'],
            'sslmode': self.config['sslmode'],
        }

        if database:
            conn_args['database'] = database
        else:
            conn_args['database'] = 'postgres'

        # libpq will use ~/.pgpass only if no password supplied
        if self.config['password_provider'] == 'pgpass':
            del conn_args['password']

        try:
            conn = psycopg2.connect(**conn_args)
        except Exception as e:
            self.log.error(e)
            raise e

        # Avoid using transactions, set isolation level to autocommit
        conn.set_isolation_level(0)
        return conn
274634
def connection(self):
        
        connection = self._get_connection()
        if connection:
            return connection
        else:
            message = "GTF database needs to be created"
            if self.install_string:
                message += ", run: %s" % self.install_string
            raise ValueError(message)
272876
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Make sure the postgresql extension for PHP is installed and enabled.
		if (!static::isSupported())
		{
			throw new \RuntimeException('PHP extension pg_connect is not available.');
		}

		/*
		 * pg_connect() takes the port as separate argument. Therefore, we
		 * have to extract it from the host string (if povided).
		 */

		// Check for empty port
		if (!($this->options['port']))
		{
			// Port is empty or not set via options, check for port annotation (:) in the host string
			$tmp = substr(strstr($this->options['host'], ':'), 1);

			if (!empty($tmp))
			{
				// Get the port number
				if (is_numeric($tmp))
				{
					$this->options['port'] = $tmp;
				}

				// Extract the host name
				$this->options['host'] = substr($this->options['host'], 0, strlen($this->options['host']) - (strlen($tmp) + 1));

				// This will take care of the following notation: ":5432"
				if ($this->options['host'] == '')
				{
					$this->options['host'] = 'localhost';
				}
			}

			// No port annotation (:) found, setting port to default PostgreSQL port 5432
			else
			{
				$this->options['port'] = '5432';
			}
		}

		// Build the DSN for the connection.
		$dsn = "host={$this->options['host']} port={$this->options['port']} dbname={$this->options['database']} " .
			"user={$this->options['user']} password={$this->options['password']}";

		// Attempt to connect to the server.
		if (!($this->connection = @pg_connect($dsn)))
		{
			throw new \RuntimeException('Error connecting to PGSQL database.');
		}

		pg_set_error_verbosity($this->connection, PGSQL_ERRORS_DEFAULT);
		pg_query('SET standard_conforming_strings=off');
	}
1055202
def _connect(self):
        

        try:
            db = pymysql.connect(user=self.user, passwd=self.passwd,
                                 host=self.host, port=self.port,
                                 db=self.shdb, use_unicode=True)
            return db, db.cursor()
        except Exception:
            logger.error("Database connection error")
            raise
523549
def connect(url=None, schema=None, sql_path=None, multiprocessing=False):
    
    if url is None:
        url = os.environ.get("DATABASE_URL")
    return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing)
507919
def connect(self):
        ''''''
        _logger.debug(__('Connecting to {0}.', self._address))

        if self._state != ConnectionState.ready:
            raise Exception('Closed connection must be reset before reusing.')

        if self._sock:
            connection_future = asyncio.open_connection(
                sock=self._sock, **self._connection_kwargs()
            )
        else:
            # TODO: maybe we don't want to ignore flow-info and scope-id?
            host = self._address[0]
            port = self._address[1]

            connection_future = asyncio.open_connection(
                host, port, **self._connection_kwargs()
            )

        self.reader, self.writer = yield from \
            self.run_network_operation(
                connection_future,
                wait_timeout=self._connect_timeout,
                name='Connect')

        if self._timeout is not None:
            self._close_timer = CloseTimer(self._timeout, self)
        else:
            self._close_timer = DummyCloseTimer()

        self._state = ConnectionState.created
        _logger.debug('Connected.')
416505
def connect(self):
        

        attempt = 0
        for i in self.max_tries_counter:
            attempt += 1
            try:
                self._conn = self._connect()
            except ConnectionError as exc:
                logger.warning('Attempt %s/%s. Connection to %s:%s failed after %sms.',
                               attempt, self.max_tries if self.max_tries != 0 else '∞',
                               self.host, self.port, self.connection_timeout)
                if attempt == self.max_tries:
                    logger.critical('Cannot connect to the Database. Giving up.')
                    raise ConnectionError() from exc
            else:
                break
992731
def add(cls, pid, connection):
        
        with cls._lock:
            cls._ensure_pool_exists(pid)
            cls._pools[pid].add(connection)
643490
def connect(self):
        
        _logger.info('Connecting to %s', self.AMQP_URL)
        while True:
            try:
                return adapters.AsyncioConnection(pika.URLParameters(self.AMQP_URL),
                                                  self.on_connection_open)
            except AMQPConnectionError:
                asyncio.sleep(1)
129082
def _connect(self):
        
        if self._connection is not None:
            raise RuntimeError('Close connection first.')
        self._connection = connect(self._database, **self._kwds)
        self._connection.isolation_level = None
411427
def _get_conn():
    '''
    
    '''
    try:
        conn = psycopg2.connect(
               host=__opts__['master_job_cache.postgres.host'],
               user=__opts__['master_job_cache.postgres.user'],
               password=__opts__['master_job_cache.postgres.passwd'],
               database=__opts__['master_job_cache.postgres.db'],
               port=__opts__['master_job_cache.postgres.port'])
    except psycopg2.OperationalError:
        log.error('Could not connect to SQL server: %s', sys.exc_info()[0])
        return None
    return conn
144519
function connect(options) {
  // Default driver is MySQL.
  activeBackend = options.driver || 'mysql';

  // Save the connection options for later use.
  connectionOptions = options;

  if (activeBackend === 'mysql') {
    // Save a reference to the MySQL client object for later use.
    activeDb = mysql.createClient(options);

    if (activeDb !== null) {
      activeDb.on('error', function (err) {
        console.log(err);
      });
    }
  }

  return activeDb;
}