2016-09-06 126 views
0

我是mongodb的新手,我在使用java驗證mongodb中的用戶名和密碼方面存在一個錯誤。任何人都可以告訴我正確的源代碼連接MongoDB與Java?目前,我有在getdb錯誤無法使用Java在MongoDB中驗證用戶名和密碼

import com.mongodb.MongoClient; 
import com.mongodb.MongoException; 
import com.mongodb.WriteConcern; 

import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.BasicDBObject; 
import com.mongodb.DBObject; 
import com.mongodb.DBCursor; 

public class Javamongodbconnection { 
    public static void main(String args[]) {  
     try{   

     MongoClient mongoClient = new MongoClient("localhost" , 27017); 
     DB db = mongoClient.getDB("company"); 
     System.out.println("Connect to database successfully"); 
     boolean auth = authenticate("Dell", "syzygy"); 
     System.out.println("Authentication: "+auth); 

     } catch(Exception e){ 
     System.err.println(e.getClass().getName() + ": " + e.getMessage()); 
     } 
    } 
} 
+0

究竟什麼是例外?如果問題出在getDB上,那意味着問題出現在您嘗試進行身份驗證之前。什麼是「驗證」方法? –

回答

0

嘗試getDB之前,您必須通過證書...

private void main() { 
    try { 
     ArrayList<MongoCredential> credentials = new ArrayList<>(); 
     credentials.add(MongoCredential.createCredential("username", "company", "password".toCharArray())); 

     MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), credentials); 
     DB db = mongoClient.getDB("company"); 
     System.out.println("Connect to database successfully"); 
     //boolean auth = authenticate("Dell", "syzygy"); 
     //System.out.println("Authentication: "+auth); 
    } catch (Exception e) { 
     System.err.println(e.getClass().getName() + ": " + e.getMessage()); 
    } 
} 
+0

其工作很好,謝謝你的回覆 –

+0

你可以標記我的答案爲已接受,請 – Judison