1
client = MongoClient('localhost',27017)
db = client[DB_NAME]
def db_connect():
#connecting to a DB in mongoDB
try:
if client.get_database(DB_NAME):
print("Connection Successful!")
return True
except:
print("Please check your connection")
return False
def db_close():
print ("Connection Getting Closed")
client.close()
我想实现一个任务,只有通过pymongo存在的连接,然后返回true,这样的功能可以继续,否则应该返回false和消息来检查连接。所以我们不会继续下去。pymongo:检查是否我们已连接到的MongoDB数据库
我该如何做到这一点?
EDIT 1:接受的解决方案
Successfully added user: {
"user" : "ash",
"roles" : [
{
"role" : "readWrite",
"db" : "myDB"
},
"clusterAdmin"
]
}
我添加使用上述代码段用户,然后用于下面的脚本。
DB_NAME = "myDB"
client = MongoClient('localhost',27017)
db = client[DB_NAME]
def db_connect():
#connecting to a DB in mongoDB
try:
if db.authenticate("ash","password"):
print("Connection Successful!")
return True
except:
print("Please check your connection")
return False
def db_close():
print ("Connection Getting Closed")
client.close()
if __name__ == "__main__":
db_connect()
db_close()
我已经使用这个代码段连接到我的DB 现在越来越连接到数据库 我在我的电脑数据库中,我使用的Ubuntu 16.04。
'成功添加用户:{ \t“用户”:“灰”, \t “角色”: \t \t { \t \t \t “角色”: “读写”, \t \t \t “DB”: “MYDB” \t \t}, \t] ' 我用它来创建我的用户 ,我使用这种方式连接到我的数据库,我无法找出什么错误,我想提出 \t \t“clusterAdmin” 。 –
那么你在验证时会犯什么错误? – elena
我找不出错误。从上面的代码可以看出,我做了一些改变。 它只是不认证。有什么办法可以搞清楚吗? –