2016-09-06 90 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