Initialize a postgresql connection by each connection string
    defined in the configuration file
550998
def init_db_conn(connection_name, connection_string, scopefunc=None):
    
    engine = create_engine(connection_string)
    session = scoped_session(sessionmaker(), scopefunc=scopefunc)
    session.configure(bind=engine)
    pool.connections[connection_name] = Connection(engine, session)
836755
def set_connection_string_by_user_input(self):
        """"""
        user_connection = input(
            bcolors.WARNING + "\nFor any reason connection to " + bcolors.ENDC +
            bcolors.FAIL + "{}".format(self.connection) + bcolors.ENDC +
            bcolors.WARNING + " is not possible.\n\n" + bcolors.ENDC +
            "For more information about SQLAlchemy connection strings go to:\n" +
            "http://docs.sqlalchemy.org/en/latest/core/engines.html\n\n"
            "Please insert a valid connection string:\n" +
            bcolors.UNDERLINE + "Examples:\n\n" + bcolors.ENDC +
            "MySQL (recommended):\n" +
            bcolors.OKGREEN + "\tmysql+pymysql://user:passwd@localhost/database?charset=utf8\n" + bcolors.ENDC +
            "PostgreSQL:\n" +
            bcolors.OKGREEN + "\tpostgresql://scott:tiger@localhost/mydatabase\n" + bcolors.ENDC +
            "MsSQL (pyodbc have to be installed):\n" +
            bcolors.OKGREEN + "\tmssql+pyodbc://user:passwd@database\n" + bcolors.ENDC +
            "SQLite (always works):\n" +
            " - Linux:\n" +
            bcolors.OKGREEN + "\tsqlite:////absolute/path/to/database.db\n" + bcolors.ENDC +
            " - Windows:\n" +
            bcolors.OKGREEN + "\tsqlite:///C:\\path\\to\\database.db\n" + bcolors.ENDC +
            "Oracle:\n" +
            bcolors.OKGREEN + "\toracle://user:passwd@127.0.0.1:1521/database\n\n" + bcolors.ENDC +
            "[RETURN] for standard connection {}:\n".format(defaults.sqlalchemy_connection_string_default)
        )
        if not (user_connection or user_connection.strip()):
            user_connection = defaults.sqlalchemy_connection_string_default
        set_connection(user_connection.strip())
790596
function init(config) {
    var promises = [];

    if (config.redis) {
        _.each(config.redis.dbs, function (idx, name) {
            promises.push(
                connectToRedis(idx, config.redis)
                    .then(function (remoteCache) {
                        caches[name] = wrapRemoteCache(remoteCache);
                        return true;
                    })
            );
        });
    }

    // initialization done once all connections established
    return Q.all(promises)
        .then(function () {
            return config;
        });
}
1314400
private void setupConnection(final Connection connection) throws ConnectionSetupException
   {
      try {
         if (networkTimeout == UNINITIALIZED) {
            networkTimeout = getAndSetNetworkTimeout(connection, validationTimeout);
         }
         else {
            setNetworkTimeout(connection, validationTimeout);
         }

         if (connection.isReadOnly() != isReadOnly) {
            connection.setReadOnly(isReadOnly);
         }

         if (connection.getAutoCommit() != isAutoCommit) {
            connection.setAutoCommit(isAutoCommit);
         }

         checkDriverSupport(connection);

         if (transactionIsolation != defaultTransactionIsolation) {
            connection.setTransactionIsolation(transactionIsolation);
         }

         if (catalog != null) {
            connection.setCatalog(catalog);
         }

         if (schema != null) {
            connection.setSchema(schema);
         }

         executeSql(connection, config.getConnectionInitSql(), true);

         setNetworkTimeout(connection, networkTimeout);
      }
      catch (SQLException e) {
         throw new ConnectionSetupException(e);
      }
   }
427978
def initialize(g, app):
    

    if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:

        # Initialize connections for console commands
        for k, v in app.config['DATABASES']['REDIS'].items():
            init_db_conn(k, **v)

        @app.before_request
        def before_request():
            """
            Assign redis connection pool to the global
            flask object at the beginning of every request
            """
            for k, v in app.config['DATABASES']['REDIS'].items():
                init_db_conn(k, **v)
            g.redis_pool = redis_pool

        if 'test' not in sys.argv:
            @app.teardown_request
            def teardown_request(exception):
                pool = getattr(g, 'redis_pool', None)
                if pool is not None:
                    pool.close()
555244
static function init()
    {
        if (SettingsDatabase::NEED_CONNECT) {
            $connection_string = 'mysql:host=' . SettingsDatabase::HOST . ';port=' . SettingsDatabase::PORT . ';dbname=' . SettingsDatabase::DBNAME;

            ORM::configure('connection_string', $connection_string);
            ORM::configure('username', SettingsDatabase::USERNAME);
            ORM::configure('password', SettingsDatabase::PASSWORD);
            ORM::configure('logging', SettingsDatabase::LOGGING);
            ORM::configure('driver_options', [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            ]);
        }
    }
943742
def populate_db(sql_path):
    """"""

    logger.info("Populating DB %s from %s", repr(DB["NAME"]), repr(sql_path))
    shell(
        'psql -U "{USER}" -h "{HOST}" -d "{NAME}" --file={sql_path}'.format(
            sql_path=sql_path, **DB
        )
    )
143245
def _connect(self):
        
        # Attempt to get a cached connection from the connection pool
        try:
            connection = self._pool_manager.get(self.pid, self)
            LOGGER.debug("Re-using connection for %s", self.pid)
        except pool.NoIdleConnectionsError:
            if self._pool_manager.is_full(self.pid):
                raise

            # Create a new PostgreSQL connection
            kwargs = utils.uri_to_kwargs(self._uri)
            LOGGER.debug("Creating a new connection for %s", self.pid)
            connection = self._psycopg2_connect(kwargs)

            self._pool_manager.add(self.pid, connection)
            self._pool_manager.lock(self.pid, connection, self)

            # Added in because psycopg2ct connects and leaves the connection in
            # a weird state: consts.STATUS_DATESTYLE, returning from
            # Connection._setup without setting the state as const.STATUS_OK
            if utils.PYPY:
                connection.reset()

            # Register the custom data types
            self._register_unicode(connection)
            self._register_uuid(connection)

        return connection
35446
@Override
    protected void initializeImpl()
    {
        //get logger
        Logger logger=this.getLogger();

        //get use persistent connection value
        this.usePersistentConnection=Boolean.parseBoolean(this.getConfigurationValue(FaxClientSpiConfigurationConstants.USE_PERSISTENT_CONNECTION_PROPERTY_KEY));
        logger.logDebug(new Object[]{"Using persistent connection: ",String.valueOf(this.usePersistentConnection)},null);
        
        //setup connection factory
        String className=this.getConfigurationValue(FaxClientSpiConfigurationConstants.CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY);
        this.connectionFactory=this.createMailConnectionFactoryImpl(className);
        if(this.connectionFactory==null)
        {
            throw new FaxException("Mail connection factory is not available.");
        }
    }
366158
public static void init(Properties configuration) {

        for (Object prop : configuration.keySet()) {
            String serverPropertyName = (String) prop;
            System.setProperty(PROPERTY_PREFIX + serverPropertyName, configuration.getProperty(serverPropertyName));
        }

        // Read system properties
        LOG.info("Using configuration provided using '-D' parameter and/or default values");
        EsigateServer.port = getProperty(PROPERTY_PREFIX, "port", PROPERTY_DEFAULT_HTTP_PORT);
        EsigateServer.controlPort = getProperty(PROPERTY_PREFIX, "controlPort", PROPERTY_DEFAULT_CONTROL_PORT);
        EsigateServer.contextPath = getProperty(PROPERTY_PREFIX, "contextPath", "/");
        EsigateServer.extraClasspath = getProperty(PROPERTY_PREFIX, "extraClasspath", null);
        EsigateServer.maxThreads = getProperty(PROPERTY_PREFIX, "maxThreads", 500);
        EsigateServer.minThreads = getProperty(PROPERTY_PREFIX, "minThreads", 40);
        EsigateServer.outputBufferSize = getProperty(PROPERTY_PREFIX, "outputBufferSize", 8 * 1024);
        EsigateServer.idleTimeout = getProperty(PROPERTY_PREFIX, "idleTimeout", 30 * 1000);
        EsigateServer.sessionCookieName = getProperty(PROPERTY_PREFIX, "sessionCookieName", null);
    }
758309
def init(cls, conn_string=None):
        """"""
        if conn_string:
            _update_meta(conn_string)
            # We initialize the engine within the models module because models'
            # schema can depend on which data types are supported by the engine
            Meta.Session = new_sessionmaker()
            Meta.engine = Meta.Session.kw["bind"]
            logger.info(
                f"Connecting user:{Meta.DBUSER} "
                f"to {Meta.DBHOST}:{Meta.DBPORT}/{Meta.DBNAME}"
            )
            Meta._init_db()

        if not Meta.log_path:
            init_logging()

        return cls
1283876
public synchronized void initialize() throws DatabaseException {
        //this only needs to be called once.
        if (connectionString != null) {
            return;
        }
        Connection conn = null;
        try {
            //load the driver if necessary
            final String driverName = settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
            final String driverPath = settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
            LOGGER.debug("Loading driver '{}'", driverName);
            try {
                if (!driverPath.isEmpty()) {
                    LOGGER.debug("Loading driver from: {}", driverPath);
                    driver = DriverLoader.load(driverName, driverPath);
                } else {
                    driver = DriverLoader.load(driverName);
                }
            } catch (DriverLoadException ex) {
                LOGGER.debug("Unable to load database driver", ex);
                throw new DatabaseException("Unable to load database driver", ex);
            }
            userName = settings.getString(Settings.KEYS.DB_USER, "dcuser");
            //yes, yes - hard-coded password - only if there isn't one in the properties file.
            password = settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
            try {
                connectionString = settings.getConnectionString(
                        Settings.KEYS.DB_CONNECTION_STRING,
                        Settings.KEYS.DB_FILE_NAME);
            } catch (IOException ex) {
                LOGGER.debug("Unable to retrieve the database connection string", ex);
                throw new DatabaseException("Unable to retrieve the database connection string", ex);
            }

            boolean shouldCreateSchema = false;
            try {
                if (connectionString.startsWith("jdbc:h2:file:")) { //H2
                    shouldCreateSchema = !h2DataFileExists();
                    LOGGER.debug("Need to create DB Structure: {}", shouldCreateSchema);
                }
            } catch (IOException ioex) {
                LOGGER.debug("Unable to verify database exists", ioex);
                throw new DatabaseException("Unable to verify database exists", ioex);
            }
            LOGGER.debug("Loading database connection");
            LOGGER.debug("Connection String: {}", connectionString);
            LOGGER.debug("Database User: {}", userName);

            try {
                if (connectionString.toLowerCase().contains("integrated security=true")
                        || connectionString.toLowerCase().contains("trusted_connection=true")) {
                    conn = DriverManager.getConnection(connectionString);
                } else {
                    conn = DriverManager.getConnection(connectionString, userName, password);
                }
            } catch (SQLException ex) {
                if (ex.getMessage().contains("java.net.UnknownHostException") && connectionString.contains("AUTO_SERVER=TRUE;")) {
                    connectionString = connectionString.replace("AUTO_SERVER=TRUE;", "");
                    try {
                        conn = DriverManager.getConnection(connectionString, userName, password);
                        settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
                        LOGGER.debug("Unable to start the database in server mode; reverting to single user mode");
                    } catch (SQLException sqlex) {
                        LOGGER.debug("Unable to connect to the database", ex);
                        throw new DatabaseException("Unable to connect to the database", ex);
                    }
                } else {
                    LOGGER.debug("Unable to connect to the database", ex);
                    throw new DatabaseException("Unable to connect to the database", ex);
                }
            }
            if (shouldCreateSchema) {
                try {
                    createTables(conn);
                } catch (DatabaseException dex) {
                    LOGGER.debug("", dex);
                    throw new DatabaseException("Unable to create the database structure", dex);
                }
            }
            try {
                ensureSchemaVersion(conn);
            } catch (DatabaseException dex) {
                LOGGER.debug("", dex);
                throw new DatabaseException("Database schema does not match this version of dependency-check", dex);
            }
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    LOGGER.debug("An error occurred closing the connection", ex);
                }
            }
        }
    }
598812
def _initialize_providers(self):
        """"""
        configured_providers = active_config.DATABASES
        provider_objects = {}

        if not isinstance(configured_providers, dict) or configured_providers == {}:
            raise ConfigurationError(
                "'DATABASES' config must be a dict and at least one "
                "provider must be defined")

        if 'default' not in configured_providers:
            raise ConfigurationError(
                "You must define a 'default' provider")

        for provider_name, conn_info in configured_providers.items():
            provider_full_path = conn_info['PROVIDER']
            provider_module, provider_class = provider_full_path.rsplit('.', maxsplit=1)

            provider_cls = getattr(importlib.import_module(provider_module), provider_class)
            provider_objects[provider_name] = provider_cls(conn_info)

        return provider_objects
801496
private function connection_init()
    {
        $opts = $this->config;

        // Headers format
        $headers = [];
        foreach ($opts['headers'] as $key => $value)
            $headers[] = "$key: $value";

        $connection = new JsonRPC\Client($opts['url'], $opts['timeout'], $headers);

        $connection->ssl_verify_peer = $opts['ssl_verify_peer'];
        $connection->debug           = $opts['debug'];
        $connection->named_arguments = isset($opts['named_arguments']) && $opts['named_arguments']===true;

        if (isset($opts['username']) && $opts['username']) {
            $connection->authentication($opts['username'], $opts['password']);
        }

        return $connection;
    }
633861
protected function _init() {
		$this->connection = $this->connection ?: new Memcached();
		$this->connection->addServers($this->_formatHostList($this->_config['host']));

		if ($this->_config['scope']) {
			$this->connection->setOption(Memcached::OPT_PREFIX_KEY, "{$this->_config['scope']}:");
		}
	}
774038
def initialize_schema(connection):
  
  cursor = connection.cursor()
  cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID))
  cursor.execute("PRAGMA user_version={}".format(_TENSORBOARD_USER_VERSION))
  with connection:
    for statement in _SCHEMA_STATEMENTS:
      lines = statement.strip('\n').split('\n')
      message = lines[0] + ('...' if len(lines) > 1 else '')
      logger.debug('Running DB init statement: %s', message)
      cursor.execute(statement)
977335
public function init()
    {
        $this->appInstance->pgsql->getConnection(function ($sql) {
            if (!$sql->connected) { // failed to connect
                $this->wakeup(); // wake up the request immediately
                $sql->release();
                return;
            }
            $sql->query('SELECT 123 as integer, NULL as nul, \'test\' as string', function ($sql, $success) {
                $this->queryResult = $sql->resultRows; // save the result
                $this->wakeup(); // wake up the request immediately
                $sql->release();
            });
        });
        $this->sleep(5);
    }