Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JDBC Question

 
Ryan Bailey
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to develop a singleton design pattern that will allow me to retrieve a connection from my database. Below is my code.

As I understand it this connection should never close since it is defined at the class level. Is this ok? Do I need to define a new connection each time I want to query a database??? I think the anwser to this question is NO.
Question number 2:
This method returns an instance of Connection. When I call this method, I use the connection, afterwards I call close on the connection reference. Does this in return close the connection instance in my singleton class???
I would say NO on this too.
For some reason my code is recieving a connection, but when it tries to execute another query with the same connection (without closing it prior) I am getting a NullPointerException. I don't see how this is happening since I'm not closing out my connections. Since it is defined as static I should have access to the same connection object throughout the lifecycle of my servlet engine, or until I close it.
Please help and correct me if I'm wrong.
I'm using Tomcat as my Servlet Engine.
Cheers,
Ryan
 
Jon Strayer
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Do I need to define a new connection each time I want to query a database??? I think the anwser to this question is NO.

You need one concurrent connection for each database. The way your code is written is fine as long as you don't use multiple threads (or have multiple objects try to connect "at the same time").

This method returns an instance of Connection. When I call this method, I use the connection, afterwards I call close on the connection reference. Does this in return close the connection instance in my singleton class???
I would say NO on this too.

The answer is "Yes". There is no difference between closing the reference in the singleton and closing the reference in the client class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic