I am trying to loop through a result set and output the content. Using a lambda, I am able to output the keys I want, but in order to fetch the value I need to reference a variable on the scope. How can I reference a variable defined outside of a lambda expression..?
public static void SQLSelect(Connection c, String sql, String table) {
ResultSet rs;
Statement stmt;
try {
stmt = c.createStatement();
rs = stmt.executeQuery("PRAGMA table_info(" + table + ")");
ArrayList al = new ArrayList();
while (rs.next()) {
al.add(rs.getString("name"));
}
rs = stmt.executeQuery(sql + " FROM " + table);
while (rs.next()) {
al.forEach((item) -> {
// complains here about local variable needing to be final
System.out.println(item + ": " + rs.getString("address"));
});
System.out.println();
}
rs.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
Variables used in lambdas have to be final or effectively final. rs is not effectively final because it is assigned twice. Simply replace the second version with another variable.
ResultSet rs2 = stmt.executeQuery(sql + " FROM " + table);
while (rs2.next()) {
al.forEach((item) -> {
// No longer complains
System.out.println(item + ": " + rs2.getString("address"));
});
System.out.println();
}
The compiler is telling you that "rs" must be effectively final. That is, you only assign value to it once and don't change it's value throughout its scope. But you have to statements on which you assign a value to rs:
rs = stmt.executeQuery("PRAGMA table_info(" + table + ")");
and
rs = stmt.executeQuery(sql + " FROM " + table);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With