How to properly use try-with-resources in Database connection?

爷,独闯天下 提交于 2020-01-25 07:52:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!