一个简单关于Berkeley DB的读写问题
import java.io.*; import com.sleepycat.je.*; import com.sleepycat.bind.tuple.*; public class BD { /** * @param args */ public void writer() { try { // 配置环境 EnvironmentConfig envConfig = new EnvironmentConfig(); // 设置配置事务 envConfig.setTransactional(true); // 如果不存在就创建环境 envConfig.setAllowCreate(true); File file = new File("E:/BDB/"); file.mkdirs(); // 创建数据库环?? Environment exampleEnv = new Environment(file, envConfig); // ??始数据库环境事务 Transaction txn = exampleEnv.beginTransaction(null, null); // 数据库配?? DatabaseConfig dbConfig = new DatabaseConfig(); // ??始数据库配置事务 dbConfig.setTransactional(true); // 如果没有数据库配置那么创?? dbConfig.setAllowCreate(true); // 数据库设置一个key是否允许存储多个值,true代表允许,默认false. dbConfig.setSortedDuplicates(false); // 打开??个数据库 Database exampleDb = exampleEnv.openDatabase(txn, "simpleDb", dbConfig); txn.commit(); DatabaseEntry keyEntry = new DatabaseEntry(); DatabaseEntry dataEntry = new DatabaseEntry(); /* put some data in */ txn = exampleEnv.beginTransaction(null, null); // 存入key,value StringBinding.stringToEntry("主键", keyEntry); StringBinding.stringToEntry("值", dataEntry); OperationStatus status = exampleDb.put(txn, keyEntry, dataEntry); if (status != OperationStatus.SUCCESS) { throw new DatabaseException("Data insertion got status " + status); } // 同步 txn.commitNoSync(); // 关闭数据?? exampleDb.close(); // 关闭环境 exampleEnv.close(); } catch (DatabaseException e) { e.printStackTrace(); } } public void read(){ try { //配置环境 EnvironmentConfig envConfig = new EnvironmentConfig(); //设置配置事务 envConfig.setTransactional(true); envConfig.setAllowCreate(true); Environment exampleEnv = new Environment(new File("E:/BDB"), envConfig); Transaction txn = exampleEnv.beginTransaction(null, null); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); dbConfig.setSortedDuplicates(false); Database exampleDb = exampleEnv.openDatabase(txn, "simpleDb", dbConfig); txn.commit(); DatabaseEntry keyEntry = new DatabaseEntry(); DatabaseEntry dataEntry = new DatabaseEntry(); /* retrieve the data */ txn = exampleEnv.beginTransaction(null, null); //打开游标 Cursor cursor = exampleDb.openCursor(txn, null); while (cursor.getNext(keyEntry, dataEntry, LockMode.DEFAULT) == OperationStatus.SUCCESS) { System.out.println("key=" + //实体转字符串 StringBinding.entryToString(keyEntry) + " data=" + StringBinding.entryToString(dataEntry)); } cursor.close(); txn.commitNoSync(); exampleDb.close(); exampleEnv.close(); } catch (DatabaseException e) { e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub BD myDB=new BD(); myDB.writer(); myDB.read(); } }