首先,我们在windows下安装mongodb数据库。
代码如下:
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; } }
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级