wood burning stoves 2.0*
The moose likes JDBC and the fly likes When to close a prepareStatement,ResultSet,Connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "When to close a prepareStatement,ResultSet,Connection" Watch "When to close a prepareStatement,ResultSet,Connection" New topic
Author

When to close a prepareStatement,ResultSet,Connection

adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
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: 19760
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30919
    
158

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: 268
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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to close a prepareStatement,ResultSet,Connection