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
?
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.