• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DriverManager.getConnection Question.

 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

I have a very basic question in JDBC. I am trying to connect to the database using JDBC.

Query:

Connection con = DriverManager.getConnection("url", "username", "password");

As per the documentation -> If successful then it returns the connection. If not then it gives an SQLException.

Please do let me know how should i check whether I have successfully got the connection to the database or not in my Java program ?

Could I check like this

if(con != null)
out.println("Successfully received the connection ");
else
out.println("Could not get the connection ....");

Thanks and Regards,
Sid
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is some problem in getting a connection getConnection is supposed to throw an SQLException

by catching this you can decide on a course of action.. in general terms if there is an opportunity to recover then take than action.. if not you bubble up the Exception.. probably wrapped in an application specific Exception
 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gamini Sirisena wrote:If there is some problem in getting a connection getConnection is supposed to throw an SQLException

by catching this you can decide on a course of action.. in general terms if there is an opportunity to recover then take than action.. if not you bubble up the Exception.. probably wrapped in an application specific Exception


but can't I check as per below:

 
joyd das
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Wrap your exception properly to understand why Connection Object is null.
You can always have a check before start using the Connection Object . Important point always close the connection on finally block

Siddharth Bhargava wrote:
Gamini Sirisena wrote:If there is some problem in getting a connection getConnection is supposed to throw an SQLException

by catching this you can decide on a course of action.. in general terms if there is an opportunity to recover then take than action.. if not you bubble up the Exception.. probably wrapped in an application specific Exception


but can't I check as per below:

 
Dave Tolls
Ranch Hand
Posts: 2095
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Siddharth Bhargava wrote:
but can't I check as per below:



But why would you when you can simply handle the exception (which is what is telling you you have no connection)?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic