日期:2014-05-16  浏览次数:20474 次

BerkeleyDB-JE Hello World(使用BaseAPI)
在进一步介绍JE之前,我们先看个BaseAPI版的Hello World,这个例子演示了JE最一般的使用方法,打开环境和Database,持久化数据,查询数据,关闭环境和Database。
/**
 * 用BaseAPI保存和获取数据
 * @author mengyang
 *
 */
public class HelloWorldByBaseAPI {
	
	private File file = new File("C:/Users/mengyang/workspace/je");
	private Environment env;
	private Database database;
	
	//建立环境
	private void setUp(){
		
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setAllowCreate(true); 
		env = new Environment(file, envConfig);
		
		DatabaseConfig dbConfig = new DatabaseConfig();
		dbConfig.setAllowCreate(true);
		database = env.openDatabase(null, "baseAPIDemo", dbConfig);
	}
	
	//保存数据
	private void save(){
		String key = "BaseAPI";
		String value = "Hello World!";
		
		try {
			DatabaseEntry keyEntry = new DatabaseEntry(key.getBytes("utf-8"));//键
			DatabaseEntry valueEntry = new DatabaseEntry(value.getBytes("utf-8"));//值
			database.put(null, keyEntry, valueEntry);//保存键值对
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	//检索数据
	private void get(){
		String key = "BaseAPI";
		String value;
		
		try {
			DatabaseEntry keyEntry = new DatabaseEntry(key.getBytes("utf-8"));//键
			DatabaseEntry valueEntry = new DatabaseEntry();//空的值
			if(database.get(null, keyEntry, valueEntry, LockMode.DEFAULT) == OperationStatus.SUCCESS){//根据键来查找
				value = new String(valueEntry.getData(), "utf-8");//找到了对于的值
				System.out.println("key:BaseAPI,value:"+value);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	//关闭环境
	private void shutDown(){
		database.close();
		env.close();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HelloWorldByBaseAPI myCase = new HelloWorldByBaseAPI();
		myCase.setUp();
		myCase.save();
		myCase.get();
		myCase.shutDown();
	}

}