Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Query about Connection Object

 
Mangala Garg
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!!
I want to know about closing the connection. How to create, use and close the connection object and what impact this open connectin object can have on the application???
I came across this piece of code.
//DataSource ds
PrepareStatement putStmt = ds.getConnection().prepareStatement("INSERT INTO TABLE_A( COL1, COL2, COL3) VALUES (?,?,?)");
I want to know what will happen to this connection object and if it will get closed automatically. If not how to close this connection?
Please help, its urgent.
Thanks,
Mangala
[ April 06, 2004: Message edited by: Bear Bibeault ]
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Connection will remain open until you explicitly close it. And you must close open Connection objects once you are finished with them or eventually your applicaiton will run out of avaliable Connecitons. This is important - so do it in a finally block.
 
Pawan Ramchandani
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
define this code in your bean
________________________________
public void closeDBConnection()
{
try{
if(st!=null) st.close();
if(!connection.isClosed()) connection.close();
}catch(Exception e)
{ e.printStackTrace(); }
}
________________________________

and called in your jsp as ds.closeDBConnection();
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pawan Ramchandani is half way right. You'd still need a finally block to make certain the Connection is closed.
 
Pawan Ramchandani
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YA I FORGOT TO MENTION THAT CODE THANKS TOREMIND ME AND CODE WILL BE
protected void finalize()
{
try{
if(st!=null) st.close();
if(!connection.isClosed()) connection.close();
}catch(Exception e)
{
System.out.println("not closing con");
e.printStackTrace();
}
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ehm, nope Pawan. finalize() is a method you supply to the garbage collector which it will call before it cleans up the Object. And since there is never any guarantee that the GC will ever cleanup your Object relying on it to free up resources is flawed. So what you should do is:

[ April 08, 2004: Message edited by: eammon bannon ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic