Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

When to close a prepareStatement,ResultSet,Connection  RSS feed

 
adeeb alexander
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Closing them in a finally block is considered best practice. This is the only way you know for sure the resources have been freed.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 36406
454
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use


That way I don't have to worry about writing the null checks/try catch on close either. I did it once .
 
adeeb alexander
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!