问题
I have looked around, but can't seem to find the answer to my question.
Here is the context : I have to connect to a Database in my Java program and execute a SQL request that I have no control over and don't know in advance. To do that I use the code below.
public Collection<HashMap<String, String>> runQuery(String request, int maxRows) {
List<HashMap<String, String>> resultList = new ArrayList<>();
DataSource datasource = null;
try {
Context initContext = new InitialContext();
datasource = (DataSource) initContext.lookup("java:jboss/datasources/xxxxDS");
} catch (NamingException ex) {
// throw something.
}
try (Connection conn = datasource.getConnection();
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(request); ) {
while (rs.next())
{
HashMap<String, String> map = new HashMap<>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
map.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getString(i));
}
resultList.add(map);
}
} catch (SQLException ex) {
// throw something.
}
return resultList;
}
The issue I am facing is : As you can see there is another parameter maxRows
that I don't use. I need to specify this to the statement
but can't do it in the try-with-resources
.
I would like to avoid increasing cognitive complexity of this method by nesting another try-with-resources
inside the first one in order to specify the max number of rows (like in this sample of code).
try (Connection conn = datasource.getConnection();
Statement statement = conn.createStatement(); ) {
statement.setMaxRows(maxRows);
try (ResultSet rs = statement.executeQuery(request); ) {
while (rs.next())
{
HashMap<String, String> map = new HashMap<>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
map.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getString(i));
}
resultList.add(map);
}
}
} catch (SQLException ex) {
// throw something.
}
Is there any way to do it with only one try-with-resources
?
回答1:
If you are fine to go for an additional method then it can be possible with only one try-resources
Instead of Statement statement = conn.createStatement();
Statement statement = createStatement(conn, maxRows);
Inside that new method, create Statement object and set the maxRows and return the statement obj.
回答2:
You can add an helper method to do it in a single try-with-resources block:
private static <T, E extends Exception> T configured(T resource, ThrowingConsumer<? super T, E> configuration) throws E {
configuration.accept(resource);
return resource;
}
private interface ThrowingConsumer<T, E extends Exception> {
void accept(T value) throws E;
}
And use it like this:
try (Connection conn = null
; Statement statement = configured(conn.createStatement(), stmt -> stmt.setMaxRows(maxRows))
; ResultSet rs = statement.executeQuery(request)) {
}
来源:https://stackoverflow.com/questions/59646348/how-to-properly-use-try-with-resources-in-database-connection