This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes JDBC and Relational Databases 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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "When to close a prepareStatement,ResultSet,Connection" Watch "When to close a prepareStatement,ResultSet,Connection" New topic

When to close a prepareStatement,ResultSet,Connection

adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
Hi all.
Consider this program
Connection conn;
PreparedStatement ps ;
ps= conn.prepareStatement("Some Query1");
rs = ps.executeQuery();;

ps= conn.prepareStatement("Some Query2");
rs = ps.executeQuery();;

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
Paul Sturrock

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

Joined: Oct 27, 2005
Posts: 20279

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.

How To Ask Questions How To Answer Questions
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33134

I use

That way I don't have to worry about writing the null checks/try catch on close either. I did it once .

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, 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 ( {
// do stuff
} finally {
DbUtil.close(conn, stmt, rs);

What is DbUtil in the above code.


I agree. Here's the link:
subject: When to close a prepareStatement,ResultSet,Connection
It's not a secret anymore!