Which code fragment demonstrates the proper way to handle JDBC resources?
A.
try {
ResultSet rs = stmt.executeQuery (query);
statement stmt = con.createStatement();
while (rs.next()) (/* . . . */)
} catch (SQLException e) {}
B.
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery (query);
while (rs.next()) (/* . . . */)
} catch (SQLException e) {}
C.
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery (query);
while (rs.next()) (/* . . . */)
} finally {
rs.close();
stmt.close();
}
D.
try {
ResultSet rs = stmt.executeQuery (query);
Statement stmt = con.createStatement();
while (rs.next()) (/* . . . */)
} finally {
rs.close();
stmt.close();
}
Explanation:
Should be B.
C will not compile – SQLException must be caught or thrown.
+1
NO! None of the answers is correct. Even disregarding the fact that (/* … */) should be {/* … */}:
A will not compile because stmt is used before it is declared
C and D will not compile, as rs and stmt are out of scope before the finally block.
So B is the only one that would compile, but does not demonstrate “the proper way”, because objects aren’t closed properly.
The proper way (from Java 7 forward) would be to use try-with-resources:
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery (query);
){
while (rs.next()){
/* … */
};
} catch (SQLException e) {}
But the objects do need to be closed properly… The code should demonstrate the “proper way” of using JDBC resources.
I do agree the SQLException needs to be caught as well, otherwise it wouldn’t compile. Maybe there’s a “throws SQLException” in the surrounding code?
Confusing question.
yeah, you’re right too
I think it’s B because try with resources should automatically have implied close statements
public static void main(String[] args) {
String url = “jdbc:mysql://localhost:3306/employeedb?zeroDateTimeBehavior=convertToNull”;
String username = “userName”;
String password = “password”;
String query = “SELECT * FROM manager WHERE id=1”;
Connection con = null;
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
//A
try {
ResultSet rs = stmt.executeQuery(query);
Statement stmt = con.createStatement();
while (rs.next()) {/* . . . */
}
} catch (SQLException e) {
}
//B
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {/* . . . */
}
} catch (SQLException e) {
}
//C
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {/* . . . */
}
} finally {
rs.close();
stmt.close();
}
//D
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {/* . . . */
}
} finally {
rs.close();
stmt.close();
}
}
Answer: B
‘rs’ e ‘stmt’ are undefined in the finally block!
b