您好,登錄后才能下訂單哦!
本文實例講述了Java操作Mongodb數據庫實現數據的增刪查改功能。分享給大家供大家參考,具體如下:
首先,我們在windows下安裝mongodb數據庫,安裝教程可查看前面一篇文章:https://www.jb51.net/article/85605.htm
代碼如下:
package io.mogo; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.WriteResult; /** * Hello world! * */ public class App { private static final String host = "localhost"; private static final int port = 27017; private static final String userName = ""; private static final String password = ""; private static final String dataBaseName = "test"; private static DB db; public static void main( String[] args ) throws Exception { System.out.println( "Hello World!" ); connMongoDB(); find("person", "name", "xiaoming"); DBObject newObj = new BasicDBObject(); newObj.put("name", "xiaoming"); newObj.put("desc", "i am xiaoming"); update("person", "name", "xiaoming", newObj); find("person", "name", "xiaoming"); } public static void connMongoDB() throws Exception { Mongo mongo = new Mongo(host, port); db = mongo.getDB(dataBaseName); if (!StringUtils.isEmpty(userName) || !StringUtils.isEmpty(password)) { db.authenticate(userName, password.toCharArray()); } } public static void find(String tableName, String key, String value){ DBObject obj = new BasicDBObject(); obj.put(key, value); DBCollection dbCollection = db.getCollection(tableName); DBCursor dbCursor = dbCollection.find(obj); while(dbCursor.hasNext()){ Map map = (Map)dbCursor.next(); System.out.println(map); } } public static boolean delete(String tableName, String key, String value){ DBObject obj = new BasicDBObject(); obj.put(key, value); DBCollection dbCollection = db.getCollection(tableName); WriteResult result = dbCollection.remove(obj); if(result.getN() > 0){ System.out.println("刪除數據成功!"); return true; }else{ return false; } } public static boolean insert(String tableName, DBObject obj){ DBCollection dbCollection = db.getCollection(tableName); long num = dbCollection.count(); dbCollection.insert(obj); if(dbCollection.count() - num > 0){ System.out.println("插入數據成功!"); return true; }else{ return false; } } public static boolean update(String tableName, String key, String value, DBObject newValue){ DBObject obj = new BasicDBObject(); obj.put(key, value); DBCollection dbCollection = db.getCollection(tableName); DBObject oldValue = dbCollection.findOne(obj); WriteResult result = dbCollection.update(oldValue, newValue); if(result.getN() > 0){ System.out.println("數據更新成功!"); return true; }else return false; } }
附:完整實例代碼點擊此處本站下載。
更多關于java相關內容感興趣的讀者可查看本站專題:《Java+MySQL數據庫程序設計總結》、《Java操作Excel技巧總結》、《Java數據結構與算法教程》、《Java文件與目錄操作技巧匯總》及《Java操作DOM節點技巧總結》
希望本文所述對大家java程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。