check database connection based on provided setting
195907
public function checkConnection()
    {
        $success = false;
        $message = '';
        $config  = $this->getPostConfiguration();

        try{
            $this->makeConnection($config);

            /**
             * Just trying to show tables with current connection
             */
            switch ($config['driver']) {
                case 'mysql':
                    $tables = Capsule::select('show tables');
                    break;

                case 'sqlite':
                    $tables = Capsule::select("SELECT * FROM sqlite_master WHERE type='table'");
                    break;

                case 'sqlsrv':
                    $tables = Capsule::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
                    break;

                case 'pgsql':
                    $tables = Capsule::select("SELECT * FROM pg_catalog.pg_tables");
                    break;
            }


            $success = true;
            $message = 'Successfully connected!';

        }catch(Exception $e){
            $success = false;
            $message = $e->getMessage();
        }

        Response::headers()->set('Content-Type', 'application/json');
        Response::setBody(json_encode(
            array(
                'success' => $success,
                'message' => $message,
                'config'  => $config
            )
        ));
    }
291270
protected function verifyConnection()
    {
        if (count(config('database.connections', [])) > 1) {
            $connections = array_keys(config('database.connections'));
            $default = array_search(config('database.default'), $connections);

            return $this->choice('Which connection do we use?', $connections, $default);
        }

        return config('database.default');
    }
635932
def db(self, connection_string=None):
        """"""

        connection_string = connection_string or self.settings["db"]

        if not hasattr(self, "_db_conns"):
            self._db_conns = {}
        if not connection_string in self._db_conns:
            self._db_conns[connection_string] = oz.sqlalchemy.session(connection_string=connection_string)

        return self._db_conns[connection_string]
1191231
public function connectionSettingsAreValid()
    {
        // if there is no adapter how can we initialize the correct validator to check it
        if (!$this->getDbAdapter()) {
            return false;
        }

        /**
         * @var MySQLConnectionSettings $connectionSettings
         */
        $connectionSettings = $this->getDbAdapter()->getConnectionSettings();
        if (!$connectionSettings) {
            return false;
        }

        return $connectionSettings->validateProperties();
    }
449733
def db_exists(name, user=None, host=None, port=None, maintenance_db=None,
              password=None, runas=None):
    '''
    
    '''

    databases = db_list(user=user, host=host, port=port,
                        maintenance_db=maintenance_db,
                        password=password, runas=runas)
    return name in databases
437200
function checkConnection(options, cb) {
    if (count < options.attempts) {
        connectServer(options, callback);
    } else {
        var avg = results.reduce(function(prev, curr) { return prev + curr.time; }, 0);
        var max = results.reduce(function(prev, curr) { return (prev > curr.time) ? prev : curr.time; }, results[0].time);
        var min = results.reduce(function(prev, curr) { return (prev < curr.time) ? prev : curr.time; }, results[0].time);

        avg = avg / results.length;
        var out = {
            address:  options.address,
            port:     options.port,
            attempts: options.attempts,
            avg:      avg,
            max:      max,
            min:      min,
            results:  results
        };

        cb(undefined, out);
    }
}
343095
def check_connection(func):
    """"""
    @wraps(func)
    def with_exception_handling(*args, **kwargs):
        """Wrap function being decorated."""
        try:
            return func(*args, **kwargs)
        except redis.exceptions.ConnectionError:
            raise ConnectionError("Unable to connect to the Redis "
                                  "Configuration Database. host = {}, "
                                  "port = {}, id = {}."
                                  .format(REDIS_HOST, REDIS_PORT,
                                          REDIS_DB_ID))
    return with_exception_handling
399646
public static boolean isH2Connection(Settings configuration) {
        final String connStr;
        try {
            connStr = configuration.getConnectionString(
                    Settings.KEYS.DB_CONNECTION_STRING,
                    Settings.KEYS.DB_FILE_NAME);
        } catch (IOException ex) {
            LOGGER.debug("Unable to get connectionn string", ex);
            return false;
        }
        return connStr.startsWith("jdbc:h2:file:");
    }
1183139
function (connectionInfo, query, params) {
    var connection;

    // Connection validation
    if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad hostname provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad username provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }

    if (typeof connectionInfo.password !== 'string') {
        return respond({
            success: false,
            data: {
                err: 'Bad password provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad database provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }


    // Return if no sql query specified
    if (query.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'No SQL query specified.'
            }
        });
    }

    // Create the connection to the database
    connection = mysql.createConnection(connectionInfo);

    // Connect to the database
    connection.connect();

    // Do the query
    connection.query(query, params, function (err, rows, fields) {
        // End the connection
        connection.end();

        // Return the error and stop
        if (err) {
            return respond({
                success: false,
                data: {
                    err: err,
                    query: query,
                    connection: connectionInfo
                }

            });
        }

        // Do the callback
        respond({
            success: true,
            data: {
                rows: rows,
                fields: fields
            }
        });
    });
}
1018886
def _check_connection(self):
        """"""
        try:
            super()._check_connection()
        except OSError as exc:
            _LOGGER.error(exc)
            self.protocol.transport.close()
            self.protocol.conn_lost_callback()
            return
        task = self.loop.call_later(
            self.reconnect_timeout + 0.1, self._check_connection)
        self.cancel_check_conn = task.cancel
649692
public function defaultDatabase($which_connection='')
    {
        $which_connection = $which_connection === '' ? $this->default_db : $which_connection;
        $adapter = $this->getAdapter($this->connectionType($which_connection));
        if ($which_connection == '') {
            $which_connection=$this->default_db;
        }

        if (count($this->connections) == 0) {
            return false;
        }

        $query = $adapter->defaultDatabase();

        $ret = false;
        $try = $this->query($query, $which_connection);
        if ($try && $this->num_rows($try) > 0) {
            $row = $this->fetch_row($try);
            $ret = $row['dbname'];
        }

        return $ret;
    }
813096
def set_settings(key, value):
    """"""
    with Database("settings") as settings:
        if value in ['0', 'false', 'no', 'off', 'False']:
            del settings[key]
            print("Disabled setting")
        else:
            print(value)
            settings[key] = value
            print("Setting saved")
609943
@Override
    public boolean isConnected(final Connection _connection)
        throws SQLException
    {
        boolean ret = false;
        final Statement stmt = _connection.createStatement();
        try {
            OracleDatabaseWithAutoSequence.LOG.debug("Checking if connected");
            final ResultSet resultset = stmt
                        .executeQuery("select product from product_component_version where product like 'Oracle%'");
            ret = resultset.next();
            resultset.close();
            if (ret) {
                // check if this database is rally one with AutoSequence by checking for a trigger.
                final ResultSet resultset2 = stmt
                            .executeQuery(" select * from user_triggers where trigger_name = 'T_CMABSTRACT_TRG'");
                ret = resultset2.next();
                resultset2.close();
            }
        } finally {
            stmt.close();
        }
        return ret;
    }
1153570
protected function hasDatabaseInfoChanged()
    {
        $settings_uri = $this->settingLocalFile;
        if (file_exists($settings_uri)) {
            $settings = file_get_contents($settings_uri);
            $match_status = preg_match_all("/\'(database|username|password|host|port|driver)\'\s=>\s\'(.+)\'\,?/", $settings, $matches);

            if ($match_status !== false) {
                $database = $this->getDatabaseInfo();
                $database_file = array_combine($matches[1], $matches[2]);

                foreach ($database->asArray() as $property => $value) {
                    if (isset($database_file[$property])
                        && $database_file[$property] != $value) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
1195271
def connection_class(self, adapter):
        """"""
        if self.adapters.get(adapter):
            return self.adapters[adapter]
        try:
            class_prefix = getattr(
                __import__('db.' + adapter, globals(), locals(),
                           ['__class_prefix__']), '__class_prefix__')
            driver = self._import_class('db.' + adapter + '.connection.' +
                                        class_prefix + 'Connection')
        except ImportError:
            raise DBError("Must install adapter `%s` or doesn't support" %
                          (adapter))

        self.adapters[adapter] = driver
        return driver
215096
protected String checkForMariaDb(DatabaseMetaData databaseMetaData, String databaseName) {
    try {
      String databaseProductVersion = databaseMetaData.getDatabaseProductVersion();
      if (databaseProductVersion != null && databaseProductVersion.toLowerCase().contains("mariadb")) {
        return MARIA_DB_PRODUCT_NAME;
      }
    } catch (SQLException ignore) {
    }

    try {
      String driverName = databaseMetaData.getDriverName();
      if (driverName != null && driverName.toLowerCase().contains("mariadb")) {
        return MARIA_DB_PRODUCT_NAME;
      }
    } catch (SQLException ignore) {
    }

    String metaDataClassName = databaseMetaData.getClass().getName();
    if (metaDataClassName != null && metaDataClassName.toLowerCase().contains("mariadb")) {
      return MARIA_DB_PRODUCT_NAME;
    }

    return databaseName;
  }
735075
public static function checkConnections($connection_name, $table, $check)
    {
        if($check === true)
        {
            $connections = DB::connection($connection_name)->table($table)->get();

            foreach($connections as $connection)
            {
                $name = $connection->name;

                try{
                    $testConnection = DB::connection($name)->getPdo();
                }catch(\Exception $e)
                {
                    $error = $e->getMessage();
                    \error_log($error);
                }
                if(!empty($testConnection) && empty($error))
                {
                    $update = DB::connection($connection_name)->table($table)->where('name', $name)->update(['status' => true]);
                }
                else
                {
                    $update = DB::connection($connection_name)->table($table)->where('name', $name)->update(['status' => false]);
                }
            }
        }
    }