File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Unable to get a Connection Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Unable to get a Connection Object" Watch "Unable to get a Connection Object" New topic

Unable to get a Connection Object

Rajat Bhatnagar

Joined: Mar 11, 2008
Posts: 22
I have a particular scenario where i have five methods in a class.
All of the methods require to connect to database to perform some operation

So what i ideally want to do is have five operation specific methods
and one DBMethod where i establish the connection and return back the connection object . i.e the signature would be like

public Connection DBObject(){
//Establishing connection with a type 4 driver


Regards<br />Rajat Bhatnagar<br /><a href="" target="_blank" rel="nofollow"></a>
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

OK, that all sounds good. What is your question?

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Rajat Bhatnagar

Joined: Mar 11, 2008
Posts: 22
Sorry for the incomplete post.

then in the other five operation specific methods i just say

Connection connection = DBObject();

However this approach is not working and i am getting a null pointer exception as the DBObject() method is not able to return a connection object.

i cannot understand as to why this is happening.
Also is this the right approach from the design perspective.
If not please let me know what's the right approach.

Thanks in advance
Rajat Bhatnagar

Joined: Mar 11, 2008
Posts: 22
I just need to get the visibility of connection type outside of the try block.

How to do it is not what i am able to find out>>

vedha vas

Joined: Jul 22, 2008
Posts: 10
Hi Rajat Bhatnagar,

In the DBConnect class you already have a field for Connection connection.
Then in the DBConnection method why again you are creating a connection variable.
Just use the above.

Code to be modified:

[Added code tags - Dave]
[ July 24, 2008: Message edited by: David O'Meara ]

Regrads,<br />Vedha.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Hopefully you meant something like this...

In theory the connection can still be null, but in practice either an SQLException or RuntimeException will be thrown.

Question: How to get the Connection outside the try scope?
Answer: Place the Connection outside the try scope.
I agree. Here's the link:
subject: Unable to get a Connection Object
It's not a secret anymore!