• Post Reply Bookmark Topic Watch Topic
  • New Topic

SingleTon Pattern for Databse Connection  RSS feed

 
sakthi moorthy
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi i am working on the website development and i want to know using Singleton Pattern for Database Connection for Website is Good Idea or not ? and if i use Singleton Pattern for Website means There are some Actions (java files ) which close connection object explicitly at that time i am getting Connection Closed Error How to Rectify this ?
 
Chandramouli Jambunathan
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
When you are handling Singleton Connection pattern for the DB connections, You have to closely watch the Connections objects handled in the other methods. you should never close the DB connections explicitly in any methods. Hope you might have closed the DB Connection somewhere inside the method and when the other method gets the DB connection, as you have declared the DB connection as static and closed earlier you have received this error. Steps to follow:

1. Create static connection in the class.
2. Receive the connection in methods and dont close it anywhere. Close only Stement,ResultSet..etc.
3. If you want to close Connection object , then Implementing Singleton Pattern is not the Right choice. Use others.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps you should use a connection pool instead. Calling close() on pooled connections usually does not really close the connection but returns it to the pool instead.

Or you could make a wrapper:

You return an instance of this wrapper instead of your actual connection. The wrapper will delegate everything to your actual connection except for the closing.
 
Chandramouli Jambunathan
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes..Connection Pooling should be mandatory always for the web based applications...
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kindly UseOneThreadPerQuestion.
You have one question related to design and the other a problem in implementation, neither of them belong to the Java Advanced forum.

Moving to the OO, Patterns, UML and refactoring forum. (All design related questions go there)
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd highly recommend to not use the Singleton Pattern - neither for a single connection, nor for a pool. See http://faq.javaranch.com/java/SingletonPattern for lots of information.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!