mongodb的密码链接

* 无密码连接mongodb服务

*/

public void connectToMongoNoPasswd() throws Exception{

//连接到 mongodb 服务

MongoClient mongoClient = new MongoClient( "192.168.1.5" , 27017 );

//连接到数据库

MongoDatabase mongoDatabase = mongoClient.getDatabase("col");

System.out.println("Connect to database successfully");

}

/**

* 设置密码连接mongodb服务

*/

public void connectToMongoByPasswd() throws Exception{

//ServerAddress()两个参数分别为 服务器地址 和 端口

ServerAddress serverAddress = new ServerAddress("192.168.1.5",27017);

List addrs = new ArrayList();

addrs.add(serverAddress);

//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码

MongoCredential credential = MongoCredential.createScramSha1Credential("username",

"databaseName", "password".toCharArray());

List credentials = new ArrayList();

credentials.add(credential);

//通过连接认证获取MongoDB连接

MongoClient mongoClient = new MongoClient(addrs,credentials);

//连接到数据库

MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");

System.out.println("Connect to database successfully");

}

MongoDB使用教程系列文章--Driver原理(初始化) 

初始化配置地址: https://yq.aliyun.com/articles/3218

你可能感兴趣的:(mongodb的密码链接)