This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

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?:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How long time can I keep a database connection open?
 
Similar Threads
Erm.. Weird compile errors.
how to see the multiple images from database
finally block is not executing
Help with servlets
how integrate MySQL and Tomcat