python 连接数据库报错command listDatabases requires authentication
python 连接数据库报错command listDatabases requires authentication, full error: {'ok': 0.0, 'errmsg': 'command listDatabases requires authentication', 'code': 13, 'codeName': 'Unauthorized'}
·
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做认证,就成功了,然后再针对目标数据库做相应的操作即可。
更多推荐
已为社区贡献1条内容
所有评论(0)