Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to initialise Database only once in a project?  RSS feed

 
Perumal Kasi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HELLO,

I am doing a project for a library management using servlets.I have to initialise the database connection only once in my project.Is there any way to do it?
 
Kalai Selvan
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Perumal,
There are many ways by which you can do this. The simplest one is you create a singleton class for handling database (which contains the connection object) and store it in the application scope.


---------------
Kalai Selvan T.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you're trying to do is extremely dangerous and (therefore) extremely bad practice.

You should use a new connection for every request, not try to use the same one over and over again as sooner rather than later you're going to be in a world of trouble.

What you CAN do (and likely should do) is use connection pooling. Many servlet engines these days have systems for that built in which you can access through JNDI, and if not there's a host of 3rd party packages available (or you can roll your own if you must).
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!