aspose file tools*
The moose likes JDBC and the fly likes How long time can I keep a database connection open? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "How long time can I keep a database connection open?" Watch "How long time can I keep a database connection open?" New topic
Author

How long time can I keep a database connection open?

Jeppe Sommer
Ranch Hand

Joined: Jan 07, 2004
Posts: 270
Hello.

I am wondering what is best practice when handling database connection in servlet. I am using a connection pool. Do we open one single database connection and use this single connection for all queries (see Case 1) or do we open and close a database connection for each query (Case 2)? Please see code example below:

CASE 1 - Keep database connection alive through whole servlet lifetime:


CASE 2 - Open and close a database connection for each query in servlet:
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30925
    
158

Case 3- Keep the connection open for a transaction and close it as soon as possible within. This is between cases 1 and 2. It's not the whole servlet, but it's not individual queries either.

Hibernate has a pattern called Open Session in View which reflects your case #1 though. As long as the queries don't take forever, it's not bad.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jeppe Sommer
Ranch Hand

Joined: Jan 07, 2004
Posts: 270
Then what if we call a method, which is doing two SQL queries without doing other stuff. Should we still close (release) the connection after each query or is faster to keep the connection open as we don't do other stuff between the two queries?:
 
Don't get me started about those stupid light bulbs.
 
subject: How long time can I keep a database connection open?