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 和一条消息来检查连接。这样我们就不会再继续了。
我怎样才能做到这一点?
编辑 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()
我已使用此代码片段连接到我的数据库 现在连接到数据库 我的 PC 中有数据库,我使用的是 Ubuntu 16.04。
最佳答案
您可能不得不在连接函数中使用 authenticate
方法,因此您可以按如下方式进行:
In [12]: client = MongoClient(DB_MACHINE, DB_PORT)
In [13]: db = client.db_name
In [16]: if db.authenticate(DB_USER, DB_PASS, source=DB_SOURCE):
# authenticated, do ...
else:
# not authenticated, not connected, do something else
关于python - 皮蒙戈 : to check if we have connected to MongoDB database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229085/