reset password
Author Message
abajpai
Posts: 52
Posted 23:48 May 22, 2011 |

Is it ok to open a connection to the database, do the necessary work, and then close the connection each time a servlet (controller) is called? or is it preferred to open a connection in the initial servlet and leave it open endlessly?

cysun
Posts: 2935
Posted 08:35 May 23, 2011 |
abajpai wrote:

Is it ok to open a connection to the database, do the necessary work, and then close the connection each time a servlet (controller) is called? or is it preferred to open a connection in the initial servlet and leave it open endlessly?

Yes.

or is it preferred to open a connection in the initial servlet and leave it open endlessly?

Don't do this. It's bad programming practice, and it may actually lead to worse performance because then all requests have to wait for the same connection.

abajpai
Posts: 52
Posted 11:18 May 23, 2011 |

Thanks professor

abajpai
Posts: 52
Posted 20:50 May 24, 2011 |

Another question regarding database connections. 

To open a connection with the database, the code needs to be surrounded by a try/catch block. After the connection is established, should the necessary work to be done with the database be done inside try block as well or out side it? I think it works either ways if the connection succeeds, and if that is the case, which one is more efficient?

cysun
Posts: 2935
Posted 20:56 May 24, 2011 |
abajpai wrote:

Another question regarding database connections. 

To open a connection with the database, the code needs to be surrounded by a try/catch block. After the connection is established, should the necessary work to be done with the database be done inside try block as well or out side it? I think it works either ways if the connection succeeds, and if that is the case, which one is more efficient?

Efficiency-wise it doesn't make any difference, but I think you have to do them inside a try-catch block because most database operations like statement.executeQuery() and resultset.next() throw SQLException.

abajpai
Posts: 52
Posted 21:21 May 24, 2011 |

You're right. Thanks professor.