• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How long time can I keep a database connection open?

 
Jeppe Sommer
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34225
341
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeppe Sommer
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic