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-with-resources
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.