• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sharing connection object within methods

 
trupti nigam
Ranch Hand
Posts: 627
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ALL,

I need to know what is the best practice for connection object sharing.

I have a method A that opens a connection object. queries the DB. There is another method call in the same method which needs a connection object.
Is it a good practice to pass the same connection object from the calling method to the called method. Or it is good if the called method has it's own connection object and closes it when it returns to the calling method.
Below are the two approaches. Let me know which one is better and why?

Approach1:
==========
public void method A()
{
connection con = null;
preparedStatement ps = null;
try{
con = getConnection();

//does the db query

method b(con);

}catch(){}
finally{//close connection object}

}

public void method B(Connection con){
//use same connection object

}

-----------------------------------------------------------------
approach2
========

public void method A()
{
connection con = null;
preparedStatement ps = null;
try{
con = getConnection();

//does the db query

method b();

}catch(){}
finally{//close connection object}

}

public void method B(){
connection con;
try{
con = getConnection();
//query the DB
}catch(){}
finally{

//close the connection object
}
}

Which one is better 1 or 2? and why?

Thanks,
Trupti
 
sathish kumar
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is no transactionality for example, if method A has a DB insert and method B has a DB insert and transaction that happened in method A is supposed to commit and after transaction B, I see a use of passing connection objects, If not open connection in each method and close the connections. Am assuming you are getting the connections from a pool.
 
trupti nigam
Ranch Hand
Posts: 627
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sathish kumar:
If there is no transactionality for example, if method A has a DB insert and method B has a DB insert and transaction that happened in method A is supposed to commit and after transaction B, I see a use of passing connection objects, If not open connection in each method and close the connections. Am assuming you are getting the connections from a pool.


The query is simple select statement.

Which aprocah is better in general 1 or 2?

Thanks,
Trupti
 
sathish kumar
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method B is clean and better one to work with.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic