简体   繁体   中英

What is the best way to create Statement and ResultSet in java

Should I initialize Statement and ResultSet in try-with-resources Statement or just initialize in try block and close Statement and ResultSet in finally block.

I need to understand the best way to implement this according to the best practices

try-with-resources Statement

try(Connection connection = DriverManager.getConnection("url");
    Statement st = connection.createStatement();
    ResultSet rs = st.executeQuery("query")){

} catch (SQLException e) {
    e.printStackTrace();
}

or try-catch with finally

Statement st = null;
        ResultSet rs = null;
        try(Connection connection = DriverManager.getConnection("url"))
        {
            st = connection.createStatement();
            rs = st.executeQuery("query");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

I believe that most of the time less code is more clean code.Secondly readability does matter if you are working with a team and your team member can not read your code properly than it's definitely your fault.

In first case its look quite simple and easily understandable for the programmer who have worked with Java7 and removes the boiler plate code of closing the resources.In the second case you first initialized with null and have finally block with try-close-catch session.It is always better to go with the clean code which is the first one and note one more thing,

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Problem with try-with-resource is you can not use the resources out of the scope of try it will be limited to try block while that's not the case in your second part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM