详解数据库基础操作及实例
废话不多说,直接上代码,注释写的比较清楚,大家参考下,
示例代码:
/**
* 插入一条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 getCollectionsNames(String DBName) throws MongoException, UnknownHostException{
return getDB(DBName).getCollectionNames();
}
/**
* 遍历聚集中的db对象集合(相当于关系数据库中的数据)
*/
public static Set getDBObjects(DBCollection collection){
Set dbObjects = new HashSet();
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 getDBNames() throws MongoException, UnknownHostException{
return getMongo().getDatabaseNames();
}
/**
* 删除数据库
*/
public static void deleteDB(String DBName) throws MongoException, UnknownHostException{
getMongo().dropDatabase(DBName);
}
用AI做供应链优化:从需求预测到库存分配的端到端工程方案实战
从 PHP 到 AI + Golang,程序员自救转型手记(五十九):前后端自定义后台入口实现
为什么 ACC Core 不能和 OpenAPI、MCP 或 gRPC 绑死?
小米cr6606刷机教程(小米cr6606如何刷机)
用AI做了6首歌曲MV后,我最大的收获不是会做了,而是干中学
VsCode 2026 (version 1.109) 安装及AI使用配置操作步骤