嵌入式數據庫——BerkeleyDB之JavaEdition

之前聽說嵌入式什麼的,就覺得好牛B的,理解比較困難,像我這種小菜鳥真是望塵莫及...

今天有機會接觸一款之前被Oracle收購的嵌入式數據庫BerkeleyDB,初接觸感覺什麼數據庫阿不一樣是存東西嘛,就網上各種找資料看資料,半天下來總算有點眉目了

JE 適合於管理海量的,簡單的數據。其中的記錄都以簡單的鍵值對保存,即key/value對。由於它操作簡單,效率較高,因此受到了廣泛的好評。

JE 下載地址:http://www.oracle.com/technology/software/products/berkeley-db/je/index.html 下載相關zip文件 解壓之後把lib下jar文件拷貝至工程中即可使用

實例:

	// 數據庫環境
	private Environment myDbEnvironment = null;
	// 數據庫配置
	private DatabaseConfig dbConfig = null;
	// //數據庫遊標
	// private Cursor myCursor = null;
	// 數據庫對象
	private Database myDatabase = null;
	// 數據庫文件名
	private String fileName = "D:\\env";
	// 數據庫名稱
	private String dbName = "sample";

	/*
	 * 打開當前數據庫
	 */
	public void openDatabase() {
		// TODO Auto-generated method stub
		try {
			System.out.println("打開數據庫: " + dbName);
			EnvironmentConfig envConfig = new EnvironmentConfig();
			envConfig.setAllowCreate(true);// 如果不存在則創建一個
			envConfig.setTransactional(true);
			// envConfig.setReadOnly(false);
			// envConfig.setTxnTimeout(10000, TimeUnit.MILLISECONDS);
			// envConfig.setLockTimeout(10000, TimeUnit.MILLISECONDS);

			// 打開一個環境
			File file = new File(fileName);
			if (!file.exists())
				file.mkdirs();
			myDbEnvironment = new Environment(file, envConfig);

			dbConfig = new DatabaseConfig();
			dbConfig.setAllowCreate(true);// 如果數據庫不存在則創建一個
			dbConfig.setTransactional(true);
			// dbConfig.setReadOnly(false);

			if (myDatabase == null)
				myDatabase = myDbEnvironment.openDatabase(null, dbName,
						dbConfig);

			// System.out.println(dbName + "數據庫中的數據個數: " + myDatabase.count());
			// 取得數據庫的名稱
			// System.out.println("數據庫名稱:"+myDatabase.getDatabaseName());
			// Environment theEnv = myDatabase.getEnvironment();//
			// 取得包含這個database的環境信息

			// theEnv.getDatabaseNames(); // 返回當前環境下的數據庫列表
			// theEnv.removeDatabase(); //刪除當前環境中指定的數據庫

			// theEnv.renameDatabase(null, null, null); // 給當前環境下的數據庫改名

			// theEnv.truncateDatabase(null,"dbName",true);
			// //清空database內的所有數據,返回清空了多少條記錄。
		} catch (DatabaseException e) {
			System.out.println(e.getMessage());
		}
	}

	/*
	 * 向數據庫中寫入記錄 傳入key和value
	 */
	public boolean writeToDatabase(String key, String value, boolean isOverwrite) {
		// TODO Auto-generated method stub
		try {
			// 設置key/value,注意DatabaseEntry內使用的是bytes數組
			DatabaseEntry theKey = new DatabaseEntry(key.trim().getBytes(
					"UTF-8"));
			DatabaseEntry theData = new DatabaseEntry(value.getBytes("UTF-8"));
			OperationStatus res = null;
			// Transaction txn = null;
			try {
				// TransactionConfig txConfig = new TransactionConfig();
				// txConfig.setSerializableIsolation(true);
				// txn = myDbEnvironment.beginTransaction(null, txConfig);
				if (isOverwrite) {
					res = myDatabase.put(null, theKey, theData);
				} else {
					res = myDatabase.putNoOverwrite(null, theKey, theData);
				}
				// txn.commit();
				if (res == OperationStatus.SUCCESS) {
					System.out.println("向數據庫" + dbName + "中寫入:" + key + ","
							+ value);
					return true;
				} else if (res == OperationStatus.KEYEXIST) {
					System.out.println("向數據庫" + dbName + "中寫入:" + key + ","
							+ value + "失敗,該值已經存在");
					return false;
				} else {
					System.out.println("向數據庫" + dbName + "中寫入:" + key + ","
							+ value + "失敗");
					return false;
				}
			} catch (LockConflictException lockConflict) {
				// txn.abort();
				System.out.println("向數據庫" + dbName + "中寫入:" + key + "," + value
						+ "出現lock異常");
				System.out.println(lockConflict.getMessage());
				System.out.println(lockConflict.getCause().toString());
				System.out.println(lockConflict.getStackTrace().toString());
				return false;
			}
		} catch (Exception e) {
			// 錯誤處理
			System.out.println("向數據庫" + dbName + "中寫入:" + key + "," + value
					+ "出現錯誤");
			return false;
		}
	}

	/*
	 * 從數據庫中讀出數據 傳入key 返回value
	 */
	public String readFromDatabase(String key) {
		// TODO Auto-generated method stub
		// Database.getSearchBoth()
		try {
			DatabaseEntry theKey = new DatabaseEntry(key.getBytes("UTF-8"));
			DatabaseEntry theData = new DatabaseEntry();
			Transaction txn = null;
			try {
				TransactionConfig txConfig = new TransactionConfig();
				txConfig.setSerializableIsolation(true);
				txn = myDbEnvironment.beginTransaction(null, txConfig);
				OperationStatus res = myDatabase.get(txn, theKey, theData,
						LockMode.DEFAULT);
				txn.commit();
				if (res == OperationStatus.SUCCESS) {
					byte[] retData = theData.getData();
					String foundData = new String(retData, "UTF-8");
					System.out.println("從數據庫" + dbName + "中讀取:" + key + ","
							+ foundData);
					return foundData;
				} else {
					System.out
							.println("No record found for key '" + key + "'.");
					return "";
				}
			} catch (LockConflictException lockConflict) {
				txn.abort();
				System.out.println("從數據庫" + dbName + "中讀取:" + key + "出現lock異常");
				System.out.println(lockConflict.getMessage());
				System.out.println(lockConflict.getCause().toString());
				System.out.println(lockConflict.getStackTrace().toString());

				return "";
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			return "";
		}
	}

	/*
	 * 遍歷數據庫中的所有記錄,返回list
	 */
	public ArrayList<String> getEveryItem() {
		// TODO Auto-generated method stub
		System.out.println("===========遍歷數據庫" + dbName
				+ "中的所有數據==========");
		Cursor myCursor = null;
		ArrayList<String> resultList = new ArrayList<String>();
		Transaction txn = null;
		try {
			txn = this.myDbEnvironment.beginTransaction(null, null);
			CursorConfig cc = new CursorConfig();
			cc.setReadCommitted(true);
			if (myCursor == null)
				myCursor = myDatabase.openCursor(txn, cc);
			DatabaseEntry foundKey = new DatabaseEntry();
			DatabaseEntry foundData = new DatabaseEntry();
			// 使用cursor.getPrev方法來遍歷遊標獲取數據
			if (myCursor.getFirst(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
				String theKey = new String(foundKey.getData(), "UTF-8");
				String theData = new String(foundData.getData(), "UTF-8");
				resultList.add(theKey);
				System.out.println("Key | Data : " + theKey + " | "
						+ theData + "");
				while (myCursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
					theKey = new String(foundKey.getData(), "UTF-8");
					theData = new String(foundData.getData(), "UTF-8");
					resultList.add(theKey);
					System.out.println("Key | Data : " + theKey
							+ " | " + theData + "");
				}
			}
			myCursor.close();
			txn.commit();
			return resultList;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			System.out.println("getEveryItem處理出現異常");
			System.out.println(e.getMessage().toString());
			System.out.println(e.getCause().toString());

			txn.abort();
			if (myCursor != null) {
				myCursor.close();
			}
			return null;
		}
	}

	/**
	 * 關閉數據庫以及環境
	 */
	public void closeDatabase() {
		try {
			if (myDatabase != null) {
				myDatabase.close();
			}
			if (myDbEnvironment != null) {
				myDbEnvironment.cleanLog();
				myDbEnvironment.close();
			}
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章