*
The moose likes JDBC 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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Unable to get a Connection Object" Watch "Unable to get a Connection Object" New topic
Author

Unable to get a Connection Object

Rajat Bhatnagar
Greenhorn

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="http://guideofgreatness.googlepages.com" target="_blank" rel="nofollow">http://guideofgreatness.googlepages.com</a>
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

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


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Rajat Bhatnagar
Greenhorn

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
Greenhorn

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
Greenhorn

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
Rancher

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.
 
wood burning stoves
 
subject: Unable to get a Connection Object
 
Similar Threads
Too many Connections Exception
synchronization
JTS and JDBC Connection relationship
Threads behaving weirdly
Driver Loading