简体   繁体   中英

Looping a result set for a condition in Java using Jackcess

Using Jackcess 2.0.4 I am trying to query the table and get all rows matching a particular condition.

Map<String, String> testData = new Hashtable<String, String>();

Database db = DatabaseBuilder.open(new File("DB.mdb"));
Table table = db.getTable("db_data");

Cursor cursor = CursorBuilder.createCursor(table);

while (cursor.findNextRow(Collections.singletonMap("case", case))) {
    Row row = cursor.getCurrentRow();

    testData.put(row.get("Key").toString(), row.get("Data").toString());
}

The value for testData is always null as no rows are returned. I am not sure what I am missing here.

I have even tried the below approach. It's still the same.

for (Row row : cursor.newIterable().addMatchPattern("TestCaseId", testCaseId)) {
    testData.put(row.get("Key").toString(), row.get("Data").toString());
}

Check your code to make sure that your column names and types exactly match those in the table. For sample data in a table named [db_data] ...

RowId  TestCaseId  Key   Data
-----  ----------  ----  -----
    1           1  key1  data1
    2           2  key2  data2
    3           1  key3  data3

... the following code ...

Map<String, String> testData = new Hashtable<String, String>();

String dbFile = "C:/Users/Public/test/DB.mdb";
try (Database db = DatabaseBuilder.open(new File(dbFile))) {
    Table table = db.getTable("db_data");
    Cursor cursor = CursorBuilder.createCursor(table);
    int testCaseId = 1;
    for (Row row : cursor.newIterable().addMatchPattern("TestCaseId", testCaseId)) {
        testData.put(row.get("Key").toString(), row.get("Data").toString());
    }

    Iterator<Map.Entry<String, String>> it = testData.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> entry = it.next();
        System.out.println(String.format(
                "Key: %s, Data: %s", 
                entry.getKey(), 
                entry.getValue()));
    }
} catch (Exception e) {
    e.printStackTrace(System.out);
}

... gives me the following console output:

Key: key3, Data: data3
Key: key1, Data: data1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM