{"record":{"id":"09a15ae9d7c80ae6","repo":"redis/redis-py","slug":"invalid-database-09a15a","errorCode":null,"errorMessage":"Invalid Database","messagePattern":"Invalid Database","errorType":"exception","errorClass":"ConnectionError","httpStatus":null,"severity":"error","filePath":"redis/connection.py","lineNumber":1240,"sourceCode":"\n        try:\n            if self.driver_info and self.driver_info.lib_version:\n                self.send_command(\n                    \"CLIENT\",\n                    \"SETINFO\",\n                    \"LIB-VER\",\n                    self.driver_info.lib_version,\n                    check_health=check_health,\n                )\n                self.read_response()\n        except ResponseError:\n            pass\n\n        # if a database is specified, switch to it\n        if self.db:\n            self.send_command(\"SELECT\", self.db, check_health=check_health)\n            if str_if_bytes(self.read_response()) != \"OK\":\n                raise ConnectionError(\"Invalid Database\")\n\n    def disconnect(self, *args, **kwargs):\n        \"Disconnects from the Redis server\"\n        # The server session is gone, so any HIMPORT fieldsets prepared on this\n        # socket no longer exist; reset the tracking.\n        self._reset_himport_state()\n        self._parser.on_disconnect()\n\n        conn_sock = self._sock\n        self._sock = None\n        # reset the reconnect flag\n        self.reset_should_reconnect()\n\n        if conn_sock is None:\n            return\n\n        if os.getpid() == self.pid:\n            try:","sourceCodeStart":1222,"sourceCodeEnd":1258,"githubUrl":"https://github.com/redis/redis-py/blob/6a6b581b48225afa0b76912d1028c6035baee932/redis/connection.py#L1222-L1258","documentation":"Raised in on_connect (connection.py:1237-1240) when db is set and the SELECT reply is not 'OK'. After authenticating, the library issues SELECT <db> to move to the configured logical database; a non-OK reply means the database index is invalid or unavailable, so the connection is aborted rather than silently running on db 0.","triggerScenarios":"Passing db=16 (or any index >= the configured number of databases) — default Redis ships 16 databases (0-15); passing a negative db; a server configured with fewer databases than the requested index.","commonSituations":"Migrating from another system with more logical DBs; typo in db index; reducing 'databases' in redis.conf without updating clients.","solutions":["Use a db index within [0, databases-1] (default 0-15).","Check CONFIG GET databases on the server and lower your db index accordingly.","Omit db to default to 0.","Prefer separate Redis instances/key prefixes over high db indexes."],"exampleFix":"# before\nr = redis.Redis(host=h, port=p, db=20)\n# after\nr = redis.Redis(host=h, port=p, db=10)  # within 0-15","handlingStrategy":"validation","validationCode":"def resolve_db(raw, max_dbs=16):\n    db = int(raw)\n    if not (0 <= db < max_dbs):\n        raise ValueError(f'db must be in [0,{max_dbs-1}], got {db}')\n    return db\n\n# optionally read the server limit:\nmaxdbs = redis.Redis(host=h, port=p).config_get('databases').get('databases', 16)\nr = redis.Redis(host=h, port=p, db=resolve_db(raw_db, int(maxdbs)))","typeGuard":"def is_valid_db(v, max_dbs=16) -> bool:\n    try:\n        return 0 <= int(v) < max_dbs\n    except (TypeError, ValueError):\n        return False","tryCatchPattern":"from redis.exceptions import ConnectionError\ntry:\n    r = redis.Redis(host=h, port=p, db=db_index)\n    r.ping()\nexcept ConnectionError as e:\n    if 'Invalid Database' in str(e):\n        r = redis.Redis(host=h, port=p, db=0)  # safe default\n    else:\n        raise","preventionTips":["Validate db against the server's 'databases' config before connecting.","Default to db 0 and use key-prefixing for namespacing instead of high indexes.","Re-check db bounds after changing redis.conf."],"tags":["database-index","configuration","connection","validation"],"backgroundTag":null,"analyzedSha":"6a6b581b48225afa0b76912d1028c6035baee932","analyzedAt":"2026-08-10T12:52:44.840Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}