铁雪资源网 Design By www.gsvan.com

详解数据库基础操作及实例

          废话不多说,直接上代码,注释写的比较清楚,大家参考下,

 示例代码:

/** 
 * 插入一条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); 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

标签:
MongoDB数据库,MongoDB数据库的使用,MongoDB数据库基础操作

铁雪资源网 Design By www.gsvan.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
铁雪资源网 Design By www.gsvan.com

评论“详解MongoDB数据库基础操作及实例”

暂无详解MongoDB数据库基础操作及实例的评论...