• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to return the new connection from this method ?  RSS feed

 
Abhijeet Rathore
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does the posted code not work?  Describe exactly what happens and what doesn't happen.  Is there an error?  Post the full error code.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the problem with that method?
Have a look at the Java™ Tutorials where there is a section about establishing a connection.
Have you got the return statement in the right place?
 
Abhijeet Rathore
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My code uses database connection frequently, so i created the below function that returns a ref to a connection to access the database.

......................................


The error is in the return statement inside the try block, IDK why but this doesn't work and the IDE still asks for a return statement ("Return Missing") at the end of the function.

Because the variable "conn" is inaccessible outside the TRY block, I tried to create a new variable "c" outside the TRY block and copied the "conn" into it, like this





But this doesn't work too, It says "C, might not have been initialized"



Question is how to get around this and somehow return "conn".

Thank you for helping.
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that it isn't possible (without the final return) to not return anything.  That's illegal because you say the method returns a type Connection.

One way to get around this is to place this code at the end: Not everyone thinks this is a good idea, but let's let that lie for now.  The code that calls createDBConnection() will have to test for null to see if a good connection was made.

Make sense?
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Define conn outside of the try block instead of c and assign it a value of null.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another possibility:
Let the Exception propagate from that method; rather than catching it, declare it, and let the calling method handle the Exception.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!