欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-17 22:38:19
详解数据库基础操作及实例           废话不多说,直接上代码,注释写的比...

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

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

 示例代码:

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

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