|
penDatabase(txn, databaseDBName,
dbConfig);
txn.commit();
Cursor cursor = myDB.openCursor(null, null);
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundValue = new DatabaseEntry();
// cursor.getPrev()与cursor.getNext()的区别:一个是从前往后读取,一个是从后往前读取
// 这里讲访问遍历数据库全部数据while循环噶为if判断,则就只读取第一条数据
while (cursor.getNext(foundKey, foundValue, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
theKey = new String(foundKey.getData(), "UTF-8");
if (theKey.equals(url)) {
return theKey;
}
}
cursor.close();
myDB.close();
exampleEnv.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 删除已经读取过的URL
public void deleteReadURL(String envHomePath, String databaseName,
String key) {
Environment mydbEnv = null;
Database myDatabase = null;
// 创建一个EnvironmentConfig配置对象
EnvironmentConfig envCfg = new EnvironmentConfig();
// 如果设置了true则表示当数据库环境不存在时候重新创建一个数据库环境,默认为false.
envCfg.setAllowCreate(true);
// 设置数据库缓存大小
// envCfg.setCacheSize(1024 * 1024 * 20);
// 事务支持,如果为true,则表示当前环境支持事务处理,默认为false,不支持事务处理。
envCfg.setTransactional(true);
try {
mydbEnv = new Environment(new File(envHomePath), envCfg);
DatabaseConfig dbCfg = new DatabaseConfig();
// 如果数据库不存在则创建一个
dbCfg.setAllowCreate(true);
// 如果设置为true,则支持事务处理,默认是false,不支持事务
dbCfg.setTransactional(true);
myDatabase = mydbEnv.openDatabase(null, databaseName, dbCfg);
DatabaseEntry keyEntry = new DatabaseEntry(key.getBytes("utf-8"));
// 删除
myDatabase.delete(null, keyEntry);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != myDatabase) {
try {
myDatabase.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
if (null != mydbEnv) {
// 在关闭环境前清理下日志
try {
mydbEnv.cleanLog();
} catch (DatabaseException e) {
e.printStackTrace();
}
try {
mydbEnv.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
mydbEnv = null;
}
}
}
public static void main(String[] args) {
OperatingDB odb = new OperatingDB();
// odb.writerURL( "c:/data/","www.163.com","data","123");
// odb.writerURL( "c:/data/","www.baidu.com","data","123");
String url = odb.readerURL("c:/data/", "data");
if(url != null){
odb.deleteReadURL("c:/data/","data",url);
}
else{
System.out.println("url is null !!!");
}
}
}
|