• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the best way to close all statements,resultset,preparedset and connection?

 
Rd Dari
Ranch Hand
Posts: 212
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I want to know about the exact and correctly way to close all the resultset and all resources of the JDBC


in Statement and ResultSet :------


which one is right way?


con.close(rs);
con.close(stmt);

OR

con.close(stmt);
con.close(rs);

and what with preparedstatement and resultset?

con.close(ps);
con.close(rs);

OR

con.close(rs);
con.close(ps);

and in the last

con.close(connection);

give me right way

Thanks in advanced!!!
 
Rob Spoor
Sheriff
Pie
Posts: 20750
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Closing should be done in reverse order of creating, in separate finally blocks. Before Java 7 I would usually do this, to ensure everything is closed:
Since Java 7 though, I use try-with-resources:
 
Rd Dari
Ranch Hand
Posts: 212
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for give me good answer, clear my all doubts about this and giving reply very soon

but what about when we use more than one statement,resultset
like


con.close(rs);
con.close(stmt);
con.close(rs1);
con.close(stmt1);
...........2
.........3 and much more
con.close(connection);




Thanks once again!!!
 
Rob Spoor
Sheriff
Pie
Posts: 20750
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my first code snippet, just put those after line 20 in a similar way. If you need to have two statements active at the same time, nest another try-finally block inside the current Statement try-finally block (making it contain the ResultSet try-finally block) or nest another try-finally block inside the current Connection try-finally block (making it contain the Statement try-finally block).

With Java 7 you can simply split the Connection part out:
or
 
Rd Dari
Ranch Hand
Posts: 212
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you sir..............
 
Rob Spoor
Sheriff
Pie
Posts: 20750
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic