python 连接数据库报错command listDatabases requires authentication

python 连接数据库报错command listDatabases requires authentication,第1张

python 连接数据库报错command listDatabases requires authentication python 连接数据库报错command listDatabases requires authentication, full error: {‘ok’: 0.0, ‘errmsg’: ‘command listDatabases requires authentication’, ‘code’: 13, ‘codeName’: ‘Unauthorized’} 错误原因是需要认证,说明连接MongoDB数据库需要用户名、密码认证。
  • 无密码连接mongoDB,代码如下:
from pymongo import MongoClient
class MongoDBConn:
    def __init__(self, host, port, db_name, user, password):
        """
        建立数据库连接
        """
        self.conn = MongoClient(host, port)
        self.mydb = self.conn[db_name]
  • 有密码认证,连接mongo数据库,代码如下:
from pymongo import MongoClient

class MongoDBConn:

    def __init__(self, host, port, db_name, user, password):
        """
        建立数据库连接
        """
        self.conn = MongoClient(host, port)
        self.db = self.conn.admin 
        self.db.authenticate(user, password)
        self.mydb = self.conn[db_name]

踩坑记录

其实中间还报了一个错误:

Authentication failed., full error: {‘ok’: 0.0, ‘errmsg’: ‘Authentication failed.’, ‘code’: 18, ‘codeName’: ‘AuthenticationFailed’}

代码中原来直接用:

self.db = self.conn[db_name]
self.db.authenticate(user, password)

直接用目标数据库做链接认证,就会报以上的错误,改用先连接系统默认数据库admin,用admin做认证,就成功了,然后再针对目标数据库做相应的 *** 作即可。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5680073.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存