您好,登錄后才能下訂單哦!
詳解數據庫基礎操作及實例
廢話不多說,直接上代碼,注釋寫的比較清楚,大家參考下,
示例代碼:
/** * 插入一條DB對象 */ public static void addDBObject(DBCollection collection,BasicDBObject object){ collection.insert(object); } /** * 根據id查詢DBObject */ public static DBObject getDBObjectById(String value) throws UnknownHostException, MongoException{ dbc = getDBCollection("company", "users").find(new BasicDBObject("_id",new ObjectId(value))); DBObject ob = null; int i = 0; while(dbc.hasNext()){ ob = dbc.next(); i++; } if(i == 1){ return ob; }else{ return null; } } /** * 根據key和value值查詢 */ public static DBObject getDBObject(String key,String value) throws UnknownHostException, MongoException{ dbc = getDBCollection("company", "users").find(new BasicDBObject(key,value)); DBObject ob = null; int i = 0; while(dbc.hasNext()){ ob = dbc.next(); i++; } if(i == 1){ return ob; }else{ return null; } } /** * 根據數據庫名獲取(新增)下面所有聚集名(表名) */ public static Set<String> getCollectionsNames(String DBName) throws MongoException, UnknownHostException{ return getDB(DBName).getCollectionNames(); } /** * 遍歷聚集中的db對象集合(相當于關系數據庫中的數據) */ public static Set<DBObject> getDBObjects(DBCollection collection){ Set<DBObject> dbObjects = new HashSet<DBObject>(); DBCursor cursor = collection.find(); while(cursor.hasNext()){ DBObject object = cursor.next(); dbObjects.add(object); } return dbObjects; } /** * 獲取/新增聚集(相當于關系數據庫表) */ public static DBCollection getDBCollection(String DBName,String collectionName) throws UnknownHostException, MongoException{ return getDB(DBName).getCollection(collectionName); } /** * 獲取/新增數據庫 */ public static DB getDB(String DBName) throws UnknownHostException, MongoException{ return getMongo().getDB(DBName); } /** * 連接數據庫 */ public static Mongo getMongo() throws UnknownHostException, MongoException{ Mongo mg = null; if(mg == null){ mg = new Mongo(); } return mg; } /** * 關閉連接 */ public static void destory(Mongo mg) { if (mg != null){ mg.close(); mg = null; } System.gc(); } /** * 獲取數據庫名 */ public static List<String> getDBNames() throws MongoException, UnknownHostException{ return getMongo().getDatabaseNames(); } /** * 刪除數據庫 */ public static void deleteDB(String DBName) throws MongoException, UnknownHostException{ getMongo().dropDatabase(DBName); }
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。