Can someone please explain how I might use Jackcess to implement the equivalent of the following SQL queries?
SELECT name FROM table WHERE id = '1'
SELECT name FROM table INNER JOIN table ON table.id = table2.id
Can someone please explain how I might use Jackcess to implement the equivalent of the following SQL queries?
SELECT name FROM table WHERE id = '1'
SELECT name FROM table INNER JOIN table ON table.id = table2.id
Re: your first query (SELECT ... FROM tableName WHERE ...)
In its simplest form you could use the "Searching for a row with a specific column value" example under "Sample code" on the main Jackcess page here, i.e.,
Table table = DatabaseBuilder.open(new File("my.mdb")).getTable("MyTable");
Row row = CursorBuilder.findRow(table, Collections.singletonMap("a", "foo"));
if(row != null) {
System.out.println("Found row where 'a' == 'foo': " + row);
} else {
System.out.println("Could not find row where 'a' == 'foo'");
}
To loop through multiple matching rows you could do something like this
Table table = DatabaseBuilder.open(new File("my.mdb")).getTable("MyTable");
Cursor cursor = CursorBuilder.createCursor(table);
while (cursor.findNextRow(Collections.singletonMap("a", "foo"))) {
Row row = cursor.getCurrentRow();
System.out.println(String.format(
"a='%s', SomeFieldName='%s'.",
row.get("a"),
row.get("SomeFieldName")));
}
or, as @jtahlborn suggests in a comment below,
Table table = DatabaseBuilder.open(new File("my.mdb")).getTable("MyTable");
Cursor cursor = CursorBuilder.createCursor(table);
for (Row row : cursor.newIterable().addMatchPattern("a", "foo")) {
System.out.println(String.format(
"a='%s', SomeFieldName='%s'.",
row.get("a"),
row.get("SomeFieldName")));
}
Re: your second query (SELECT ... FROM table1 INNER JOIN table2 ON ...)
You could use one for
or while
loop (similar to above) to iterate through the relevant rows in one table, and use an inner for
or while
loop to iterate through the related rows in the other (related) table. If the two tables have an existing "Relationship" in Access (a.k.a. "foreign key constraint") Jackcess has a Joiner class that may be of assistance, discussed here.