简体   繁体   中英

How to close Connection and statement inside return method?

This is one method in my project. I want to close 'con' and 'st'. How to do that?

public static int howManyPassengersInCabin(int i) throws SQLException {
    Connection con = connectionForDB();
    String query = "SELECT Capacity FROM cabin WHERE Cabin_ID = "+ i;
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery(query);
    rs.next();
    return  rs.getInt("Capacity");
}

Use try-with-resources:

public static int howManyPassengersInCabin(int i) throws SQLException {
    String query = "SELECT Capacity FROM cabin WHERE Cabin_ID = "+ i;
    try (Connection con = connectionForDB();
         Statement st = con.createStatement();
         ResultSet rs = st.executeQuery(query)) {

        rs.next();
        return  rs.getInt("Capacity");
    }
}

I could have used three nested try statements, but by reordering the code a bit I could combine them.

  • Try to use try-with-resources
  • Try to use prepared statement

For Examples:

private static final QUERY_SQL = "SELECT Capacity FROM cabin WHERE Cabin_ID=?”;

public static int howManyPassengersInCabin(int i) throws SQLException {
                try (Connection con = connectionForDB()){
             try(PreparedStatement pstmt = con.preparedStatement(QUERY_SQL)){
                 pstmt.setInt(1, i);
                 try(ResultSet rs = st.executeQuery()){
                     while(rs.next()){
                         return  rs.getInt("Capacity");
                     }
                 }
             }
        }
    }

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