Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

How long time can I keep a database connection open?

 
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:
 
author & internet detective
Posts: 40200
816
Eclipse IDE VI Editor Java
  • 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?:
 
Won't you please? Please won't you be my neighbor? - Fred Rogers. Tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic