Which code fragment demonstrates the proper way to handle JDBC resources?

Which code fragment demonstrates the proper way to handle JDBC resources?

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.



Leave a Reply 9

Your email address will not be published. Required fields are marked *


Robertinho

Robertinho

but there is error (RS – STMT )can not be reached in the FINALLY

Serg

Serg

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){}

Bahaa Khateib

Bahaa Khateib

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.

Tim

Tim

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.

Shamitha Silva

Shamitha Silva

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.

Michael

Michael

I think C is better because SQLException can be throw out.