Berkeley DB 數據庫的使用示例,je

code

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import com.sleepycat.je.Cursor;
import com.sleepycat.je.CursorConfig;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockConflictException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.TransactionConfig;

public class BDB {
	// 數據庫環境
	private Environment env = null;

	// 數據庫
	private final Database frontierDatabase;

	// 數據庫名
	private final String dbName;

	public BDB(String homeDirectory,String dbName) {

		// 一、建立EnvironmentConfig
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setTransactional(false);
		envConfig.setAllowCreate(true);

		// 二、使用EnvironmentConfig配置Environment
		env = new Environment(new File(homeDirectory), envConfig);

		// 三、建立DatabaseConfig
		DatabaseConfig dbConfig = new DatabaseConfig();
		dbConfig.setTransactional(false);
		dbConfig.setAllowCreate(true);

		// 四、使用Environment與DatabaseConfig打開Database
		frontierDatabase = env.openDatabase(null, dbName, dbConfig);
		this.dbName = dbName;
	}

	/*
	 * 向數據庫中寫入記錄,並判斷是否能夠有重複數據。 傳入key和value
	 * 若能夠有重複數據,則直接使用put()便可,若不能有重複數據,則使用putNoOverwrite()。
	 */
	public boolean writeToDatabase(String key, String value, boolean isOverwrite) {
		try {
			// 設置key/value,注意DatabaseEntry內使用的是bytes數組
			DatabaseEntry theKey = new DatabaseEntry(key.getBytes("UTF-8"));
			DatabaseEntry theData = new DatabaseEntry(value.getBytes("UTF-8"));
			OperationStatus status = null;
			Transaction txn = null;
			try {
				// 一、Transaction配置
				TransactionConfig txConfig = new TransactionConfig();
				txConfig.setSerializableIsolation(true);
				txn = env.beginTransaction(null, txConfig);
				// 二、寫入數據
				if (isOverwrite) {
					status = frontierDatabase.put(txn, theKey, theData);
				} else {
					status = frontierDatabase.putNoOverwrite(txn, theKey, theData);
				}
				txn.commit();
				if (status == OperationStatus.SUCCESS) {
//					System.out.println("向數據庫" + dbName + "中寫入:" + key + "," + value);
					return true;
				} else if (status == 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異常");
				return false;
			}
		} catch (Exception e) {
			// 錯誤處理
			System.out.println("向數據庫" + dbName + "中寫入:" + key + "," + value + "出現錯誤");

			return false;
		}
	}

	/*
	 * 從數據庫中讀出數據 傳入key 返回value
	 */
	public String readFromDatabase(String key) {
		try {
			DatabaseEntry theKey = new DatabaseEntry(key.getBytes("UTF-8"));
			DatabaseEntry theData = new DatabaseEntry();
			Transaction txn = null;
			try {
				// 一、配置 Transaction相關信息
				TransactionConfig txConfig = new TransactionConfig();
				txConfig.setSerializableIsolation(true);
				txn = env.beginTransaction(null, txConfig);
				// 二、讀取數據
				OperationStatus status = frontierDatabase.get(txn, theKey, theData, LockMode.DEFAULT);
				txn.commit();
				if (status == OperationStatus.SUCCESS) {
					// 三、將字節轉換成String
					byte[] retData = theData.getData();
					String value = new String(retData, "UTF-8");
					System.out.println("從數據庫" + dbName + "中讀取:" + key + "," + value);
					return value;
				} else {
					System.out.println("No record found for key '" + key + "'.");
					return "";
				}
			} catch (LockConflictException lockConflict) {
				txn.abort();
				System.out.println("從數據庫" + dbName + "中讀取:" + key + "出現lock異常");
				return "";
			}

		} catch (UnsupportedEncodingException e) {
			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.env.beginTransaction(null, null);
			CursorConfig cc = new CursorConfig();
			cc.setReadCommitted(true);
			if (myCursor == null)
				myCursor = frontierDatabase.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) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			System.out.println("getEveryItem處理出現異常");

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

	/*
	 * 根據key值刪除數據庫中的一條記錄
	 */
	public boolean deleteFromDatabase(String key) {
		boolean success = false;
		long sleepMillis = 0;
		for (int i = 0; i < 3; i++) {
			if (sleepMillis != 0) {
				try {
					Thread.sleep(sleepMillis);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				sleepMillis = 0;
			}
			Transaction txn = null;
			try {
				// 一、使用cursor.getPrev方法來遍歷遊標獲取數據
				TransactionConfig txConfig = new TransactionConfig();
				txConfig.setSerializableIsolation(true);
				txn = env.beginTransaction(null, txConfig);
				DatabaseEntry theKey;
				theKey = new DatabaseEntry(key.getBytes("UTF-8"));

				// 二、刪除數據 並提交
				OperationStatus res = frontierDatabase.delete(txn, theKey);
				txn.commit();
				if (res == OperationStatus.SUCCESS) {
					System.out.println("從數據庫" + dbName + "中刪除:" + key);
					success = true;
					return success;
				} else if (res == OperationStatus.KEYEMPTY) {
					System.out.println("沒有從數據庫" + dbName + "中找到:" + key + "。沒法刪除");
				} else {
					System.out.println("刪除操做失敗,因爲" + res.toString());
				}
				return false;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return false;
			} catch (LockConflictException lockConflict) {
				System.out.println("刪除操做失敗,出現lockConflict異常");
				sleepMillis = 1000;

				continue;
			} finally {
				if (!success) {
					if (txn != null) {
						txn.abort();
					}
				}
			}
		}
		return false;
	}

	public void closeDB() {
		if (frontierDatabase != null) {
			frontierDatabase.close();
		}
		if (env != null) {
			env.close();
		}
	}
}
相關文章
相關標籤/搜索