我使用Berkley DB创建了一个数据库,该数据库存储N条记录,其中记录是键/值对。我最初只用20条记录填充它。有20条记录,我设法进行密钥搜索和数据搜索(我通过记录搜索数据库记录,查找与用户输入的字符串数据相匹配的数据值)。
public String dataSearch (String dataInput) {
String foundKey = null;
String foundData = null;
Cursor cursor = null;
try {
cursor = myDb.openCursor(null, null);
DatabaseEntry theKey = new DatabaseEntry();
DatabaseEntry theData = new DatabaseEntry();
while (cursor.getNext(theKey, theData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
foundKey = new String(theKey.getData(), "UTF-8");
foundData = new String(theData.getData(), "UTF-8");
// this is to see each key - data - inputdata as I was having an issue
System.out.println("KEY: " + foundKey +
"\nDATA: " + foundData +
"\nINPUT_DATA: " + dataInput + "\n\n");
if (foundData.equals(dataInput)) {
System.out.println("-----------------------------------\n\n");
System.out.println("Found record: " + foundKey +
"\nwith data: " + foundData);
System.out.println("\n\n-----------------------------------");
}
}
/* I then close the cursor and catch exceptions and such */
当我有少于(或等于)20条记录时,这种方法很好......但是当我使用更大的数字时,我似乎有一些有趣的行为。我将记录数设置为1000 ...要插入数据库的最后一个键/数据值是:
KEY: zghxnbujnsztazmnrmrlhjsjfeexohxqotjafliiktlptsquncuejcrebaohblfsqazznheurdqbqbxjmyqr
DATA: jzpqaymwwnoqzvxykowdhxvfbuhrsfojivugrmvmybbvurxmdvmrclalzfscmeknyzkqmrcflzdooyupwznvxikermrbicapynwspbbritjyeltywmmslpeuzsmh
我打印出要插入数据库的最后一个值然后对上面的键进行了一次键搜索,以确保上面的数据实际上是与数据库中该键相关的数据。但是,当我对上面列出的数据进行数据搜索时,我找不到匹配的记录(而当有20条记录时,同一进程找到了记录)。我对它进行了一些调查并获得了每个数据搜索,以打印它返回的每个键/数据对,并找到以下结果:
KEY: zghxnbujnsztazmnrmrlhjsjfeexohxqotjafliiktlptsquncuejcrebaohblfsqazznheurdqbqbxjmyqrpzlyvnmdlvgyvzhbceeftcqssbeckxkuepxyphsgdzd
DATA: jzpqaymwwnoqzvxykowdhxvfbuhrsfojivugrmvmybbvurxmdvmrclalzfscmeknyzkqmrcflzdooyupwznvxikermrbicapynwspbbritjyeltywmmslpeuzsmhozy
INPUT DATA: jzpqaymwwnoqzvxykowdhxvfbuhrsfojivugrmvmybbvurxmdvmrclalzfscmeknyzkqmrcflzdooyupwznvxikermrbicapynwspbbritjyeltywmmslpeuzsmh
正如您所看到的,它似乎随机地将一些额外的字节附加到数据值。但是如果我进行密钥搜索,这些额外的字节就不会显示出来。所以我认为问题出在dataSearch函数中。如果我使用b + tree或hash,会出现相同的结果。
任何想法?
由于
答案 0 :(得分:0)
经过很长一段时间的观察,我意识到我的错误是我没有重新启动theKey&数据变量。
修复程序在while循环中
while (cursor.getNext(theKey, theData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
foundKey = new String(theKey.getData(), "UTF-8");
foundData = new String(theData.getData(), "UTF-8");
// this is to see each key - data - inputdata as I was having an issue
System.out.println("KEY: " + foundKey +
"\nDATA: " + foundData +
"\nINPUT_DATA: " + dataInput + "\n\n");
if (foundData.equals(dataInput)) {
System.out.println("-----------------------------------\n\n");
System.out.println("Found record: " + foundKey +
"\nwith data: " + foundData);
System.out.println("\n\n-----------------------------------");
}
// THIS IS THE FIX
theKey = new DatabaseEntry();
theData = new DatabaseEntry();
// ----------------------------
}