您的位置:首页 > 数据库 > Mongodb

使用Java 连接MongoDB3.X 3.04 带 auth 认证

2015-08-11 13:28 561 查看
/**
* 测试MongoDB连接
*/
private static void testMongoDBConn() {
MongoClient client = null;
try {
// 用户名 数据库 密码
MongoCredential credential = MongoCredential.createCredential("guoxin01", "guoxin", "123456".toCharArray());
//IP port
ServerAddress addr = new ServerAddress("192.168.1.137", 27017);
client = new MongoClient(addr,Arrays.asList(credential));
//得到数据库
MongoDatabase mdb = client.getDatabase("guoxin");
//得到Table
MongoCollection<?> table = mdb.getCollection("blog");
//查询所有
FindIterable<?> fi = table.find();
//遍历结果
for (Object o : fi) {
System.out.println(o);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (client != null) {
client.close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: