This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes JDBC and the fly likes When to close a prepareStatement,ResultSet,Connection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Databases » JDBC
Reply 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: 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
    
  78

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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to close a prepareStatement,ResultSet,Connection
 
Similar Threads
Using a Bean for Retrieving Results Sets - Best Approach
bind variable
performance issue in iterating through large list of result set
idiom for finally closing resources
Not able to navigate the user to another jsp in servlets using RequestDispatcher