Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unable to get a Connection Object

 
Rajat Bhatnagar
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

}
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, that all sounds good. What is your question?
 
Rajat Bhatnagar
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic