commonutil

package com.mongo.db;


import java.util.ArrayList;
import java.util.List;


import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;


public class MongoDBCommonUtil {


public static DB getDB(String host, int port, String database,
String username, String password) {
DB db = null;
try {
// 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
// ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress(host, port);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);


// MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential
.createScramSha1Credential(username, database,
password.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);


// 通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs, credentials);
db = mongoClient.getDB(database);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return db;
}


public static DB getDBNoUser(String host, int port, String database) {
DB db = null;
try {
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient(host, port);


// 连接到数据库
db = mongoClient.getDB(database);
System.out.println("Connect to database successfully");


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


public static void main(String[] args) {
// DB db = MongoDBCommonUtil.getDB("", 27017, "admin", "dev",
// "Init1234");
// System.out.println(db.toString());

DB db = MongoDBCommonUtil.getDBNoUser("localhost", 27017, "admin");
System.out.println(db.toString());
}


public static DBCollection getCollection(MongoDBCursor mongoDBCursor) {
// TODO Auto-generated method stub
DB db = mongoDBCursor.getDb();
DBCollection collection = db.getCollection(mongoDBCursor
.getCollectionName());
return collection;
}


public static DBCollection getCollection(MongoDBEntity mongoDBEntity) {
// TODO Auto-generated method stub
DB db = mongoDBEntity.getDb();
DBCollection collection = db.getCollection(mongoDBEntity
.getCollectionName());
return collection;
}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值