File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC and the fly likes JDBC Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "JDBC Question" Watch "JDBC Question" New topic
Author

JDBC Question

Ryan Bailey
Ranch Hand

Joined: Feb 26, 2002
Posts: 134
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


SCJP 1.4, SCWCD
Java: The power, elegance, and simplicity of a hand grenade
Jon Strayer
Ranch Hand

Joined: Dec 04, 2002
Posts: 133

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.


Jon
 
Consider Paul's rocket mass heater.
 
subject: JDBC Question