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
我找不出錯誤。從上面的代碼可以看出,我做了一些改變。 它只是不認證。有什麼辦法可以搞清楚嗎? –