Search code examples
javajackcess

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());
}

Solution

  • 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