国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java操作mongoDB的方法中mongo和mongoClient區(qū)別

2019-11-08 00:50:34
字體:
供稿:網(wǎng)友

mongo和mongoClient區(qū)別

兩個方法都是可以實現(xiàn)連接mongodb

mongo方法

import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.Mongo; public class Test { public static void main(String[] args) { try { /**** Connect to MongoDB ****/ // Since 2.10.0, uses MongoClient //MongoClient mongo = new MongoClient("localhost", 27017); Mongo mongo = new Mongo("127.0.0.1",27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("testMongoDb"); //database username root and passWord root boolean ok = db.authenticate("root","root".toCharArray()); if(ok){ System.out.使用mongoClient方法

static final String DBName = "weibo"; static final String ServerAddress = "127.0.0.1"; static final int PORT = 27017; public MongoHelper(){ } public MongoClient getMongoClient( ){ MongoClient mongoClient = null; try { // 連接到 mongodb 服務(wù) mongoClient = new MongoClient(ServerAddress, PORT); System.out.println("Connect to mongodb successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } return mongoClient; } public MongoDatabase getMongoDataBase(MongoClient mongoClient) { MongoDatabase mongoDataBase = null; try { if (mongoClient != null) { // 連接到
數(shù)據(jù)庫 mongoDataBase = mongoClient.getDatabase(DBName); System.out.println("Connect to DataBase successfully"); } else { throw new RuntimeException("MongoClient不能夠為空"); } } catch (Exception e) { e.printStackTrace(); } return mongoDataBase; } public void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) { if (mongoDataBase != null) { mongoDataBase = null; } if (mongoClient != null) { mongoClient.close(); } System.out.println("CloseMongoClient successfully"); }

區(qū)別: 參考:http://blog.itpub.net/30341463/viewspace-1758585/ 官方文檔和源代碼均建議使用MongoClient類,而且,在不久的將來,會廢棄Mongo類。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新巴尔虎右旗| 巴青县| 竹北市| 彰武县| 萨嘎县| 开远市| 汤原县| 兴海县| 闽清县| 东兴市| 蓝田县| 九龙城区| 韶关市| 中山市| 商水县| 远安县| 景德镇市| 郑州市| 襄汾县| 嘉峪关市| 岳池县| 石城县| 健康| 江北区| 科尔| 旅游| 海原县| 青龙| 仁化县| 三穗县| 曲周县| 绥化市| 正镶白旗| 五莲县| 滦平县| 炉霍县| 大关县| 玉田县| 瑞昌市| 高唐县| 汉阴县|