Which code fragment demonstrates the proper way to handle JDBC resources?
A.
Try {
ResultSet rs = stmt.executableQuery (query);
statement stmt = con.createStatement();
while (rs.next()) (/* . . . */)
} catch (SQLException e) {}
B.
Try {statement stmt = con.createStatement();
ResultSet rs = stmt.executableQuery (query);
while (rs.next()) (/* . . . */)
} catch (SQLException e) {}
C.
Try {
statement stmt = con.createStatement();
ResultSet rs = stmt.executableQuery (query);
while (rs.next()) (/* . . . */)
} finally {
rs.close();
stmt.close();
}
D.
Try {ResultSet rs = stmt.executableQuery (query);
statement stmt = con.createStatement();
while (rs.next()) (/* . . . */)
} finally {
rs.close();
stmt.close();
}
Explanation:
We should use the finally statement to gracefully close the connection.
but there is error (RS – STMT )can not be reached in the FINALLY
c. Error:
rs cannot be resolved
stmt cannot be resolved
I’m think “B” is correct.
We should CONNECTION “open” and “close”, but we have connection “open”. We don’t must it “close” in this exercise.
We should use the finally statement to gracefully close the Connection
Connection con ;
String query = “…”
Statement stmt;
ResultSet rs;
try {
con = ….. ;
stmt = con.createStatement();
rs = stmt.executableQuery (query);
while (rs.next()) (/* . . . */)
} finally {
try{ rs.close();} catch(SQLExeption ex1){}
try{ stmt.close();} catch(SQLExeption ex1){}
try{ con.close();} catch(SQLExeption ex1){}
}
but
,
OR try-with-resources Statement.
Try(
Connection con = … .
Statement stmt = con.createStatement();
ResultSet rs = stmt.executableQuery (query);
){
while (rs.next()) (/* . . . */)
}
catch(SQLException ex){}
+1
B
There is no way C is the answer, I will go with “B”, but I think the choices are wrong the desired answer might contain con declared out try and close resources in finally block.
B. The code of option C won’t compile. BTW, SQLException is a checked exception, and must be caught in the try-catch block. In the meanwhile, as Serg’s words, we don’t necessarily need to close the resources.
No C will compile, a try block must follow a one or more catch block and/or a finally block, since the question is about resource closing I think C is correct.
b
I think C is better because SQLException can be throw out.