| Author |
When to close a prepareStatement,ResultSet,Connection
|
adeeb alexander
Ranch Hand
Joined: May 29, 2008
Posts: 267
|
|
Hi all.
Consider this program
try
{
Connection conn;
PreparedStatement ps ;
ps= conn.prepareStatement("Some Query1");
rs = ps.executeQuery();
rs.next();
ps= conn.prepareStatement("Some Query2");
rs = ps.executeQuery();
rs.next();
}
catch(Exception ce)
{
}
Like above i used one try block for may statements and preparedStatements to execute. Now Someone please tell me where shall i close all these. can i close in between or at the end of try block?
Thanks and Regards
alexander
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
Closing them in a finally block is considered best practice. This is the only way you know for sure the resources have been freed.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
I usually use nested try-finally blocks:
I know it looks weird, and I have to write 3 levels of try-finally blocks, but I won't have to declare the PreparedStatement and ResultSet at the start with a value of null, then have to check if they are null before closing them.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26499
|
|
I use
That way I don't have to worry about writing the null checks/try catch on close either. I did it once .
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
adeeb alexander
Ranch Hand
Joined: May 29, 2008
Posts: 267
|
|
Very late reply but a doubt guyz.
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(...);
stmt = conn.prepareStatement(...);
rs = stmt.executeQuery();
while (rs.next()) {
// do stuff
}
} finally {
DbUtil.close(conn, stmt, rs);
}
What is DbUtil in the above code.
Thanks.
|
 |
 |
|
|
subject: When to close a prepareStatement,ResultSet,Connection
|
|
|