The Java tutorial state that you can do the following with try-with-resources
:
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
...
} catch (SQLException e) {
...
}
In this tutorial the ResultSet
is never closed, thus I want to include the ResultSet
, as it also implements the AutoCloseable
interface, like so:
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
...
} catch (SQLException e) {
...
}
This works fine, but when it comes to PreparedStatements
I want to be able to set some values on the before executing the query:
String name = "Ian";
try (PreparedStatement pstmt = getPreparedStatement(con, stmt);
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery(query)) {
...
} catch (SQLException e) {
...
}
This causes a range of compilation errors, because (I am assuming) only variable assignment is allowed.
Is there anyway to do this neatly in the same try-with-resources
block?
I have already thought of:
- Nested try-with-resources (which is what I am trying to avoid). I realise there is nothing 'wrong' with doing so, I merely want to do this for the sake of readability.
Consider the following to cases:
try (MyObject1 o1 = new MyObject1()) {
o1.setSomeValue();
try (MyObject2 o2 = new MyObject2(o1)) {
o2.setSomeValue();
try (MyObject3 o3 = new MyObeject3(o2) {
o3.setSomeValue();
// do work here
}
}
} catch (Exception e) {
...
}
vs
try (MyObject1 o1 = new MyObject1();
o1.setSomeValue();
MyObject3 o2 = new MyObeject2(o1);
o2.setSomeValue();
MyObject3 o3 = new MyObeject3(o2);
o3.setSomeValue()) {
// do work here
} catch (Exception e) {
...
}
- Having
setString()
method return the object and include it in assignment - Creating some sort of helper method that creates the connection and sets parameters accordingly.
Something like:
public PreparedStatement createPreparedStatement(Connection con, String stmt, Object ... params) {
}