一、Db4o的数据库连接(ObjectContainer)
1、指定数据库存放的物理地址
final static String DB4OFILENAME = System.getProperty("user.home") + "/formula1.db4o";
2、
使用ObjectContainer获得数据库连接,并在存储完成后关闭数据库连接
ObjectContainer container = Db4oEmbedded.openFile(DB4OFILENAME);
try{//对数据库进行管理
}finally{
container.close();
}
二、向Db4o数据库存储对象(store)
/**
* 面向对象数据的存储
* @param obj类的实例
*/
public void dataStore(Object obj){//初始化数据库连接并打开
ObjectContainer db=Db4oEmbedded.openFile(Db4oEmbedded
.newConfiguration(), DB4OFILENAME);
try {
db.store(obj);//存储语句就是这个关键字store
}
finally {
db.close();//关闭数据库连接
}
}
三、从Db4o数据库中查询对象(NQ查询方式)
ObjectContainer container = Db4oEmbedded.openFile("DB4OFILENAME.db4o");
try {//Pilot的List
List<Pilot> pilots = container.query(new Predicate<Pilot>() {
public boolean match(Pilot o) {
return o.getName().container("Joe");
}//container模糊查询
});//从List表中逐个找出Pilot对象
for (Pilot pilot : pilots) {
System.out.println(pilot.getName());
}
} finally {
container.close();
}
四、更新Db4o数据库中的对象(NQ查询方式,set方法,store方法)
ObjectContainer container = Db4oEmbedded.openFile("DB4OFILENAME");
try {//Pilot的List
List<Pilot> pilots = container.query(new Predicate<Pilot>() {
public boolean match(Pilot o) {//查询
return o.getName().equals("Joe");
}//equals方法是一个精确查询。
});//取List中的第一条数据。
Pilot aPilot = pilots.get(0);
//通过对象的Set方法对“值”重置
aPilot.setName("New Name");
// store方法进行update
container.store(aPilot);
} finally {
container.close();
}
五、更新Db4o数据库中的对象(NQ查询方式,delete方法)
ObjectContainer container = Db4oEmbedded.openFile("DB4OFILENAME");
try {//Pilot的List
List<Pilot> pilots = container.query(new Predicate<Pilot>() {
public boolean match(Pilot o) {
return o.getName().equals("Joe");
}//equals精确查询
});//取得List的第一条数据
Pilot aPilot = pilots.get(0);
//delete完成删除操作
container.delete(aPilot);
} finally {
container.close();
}