Re: Problem with connecting to postgres using jdbc7.0-1.2.jar - Mailing list pgsql-jdbc

From Jens Carlberg
Subject Re: Problem with connecting to postgres using jdbc7.0-1.2.jar
Date
Msg-id 3C29FD95.3298CD9C@lysator.liu.se
Whole thread Raw
In response to Problem with connecting to postgres using jdbc7.0-1.2.jar  (Peter Adamek <peter.adamek@utoronto.ca>)
List pgsql-jdbc
<snip>
> Here is my servlet (it compiles without any problems).

I've trimmed it to save some space, keeping just the part I have
comments on.

>     public void init (ServletConfig config) throws ServletException {
>         super.init(config);
>
>         /* Load the driver */
>         try {Class.forName("org.postgresql.Driver");}
>         catch (ClassNotFoundException e) {}

While this is an effective way to make the class compile, it raises a
couple of questions:

1. What do you do if the driver class isn't available? If your
application won't work without it, perhaps you should throw a
'show-stopper' instead.

2. Do the JVM find the driver class? The least you should do is _log_
the exception; if you see that message, you'll know the problem lies
with finding the driver.

>         /* Connect to the database */
>         try {db =
> DriverManager.getConnection("jdbc:postgresql:peter","padamek","");}

This doesn't look right to me. Isn't the syntax
jdbc:postgresql://host-name/db-name?

>         catch (SQLException e) {}

OK, your class compiles, but once again you're left without a clue on
why the application doesn't do what you expect. Place a log statement
inside the catch, and you'll be a lot wiser if this is where is goes
awry.

>     }
<snip>
>         try {
>             Statement sql = db.createStatement();

My guess is that db weren't initialized properly in the init() method.
Thus the above statement generates a NullPointer exception. If you want
to be sure, check for db == null and print something instead of trying
to query the DB.

<snip>

> Does anyone have any suggestions?  It seems strage to me that if I
> change the driver name that reads
> Class.forName("org.postgresql.Driver"), I get no errors when I compile.

Since it's a string that will be used at runtime to identify a class, it
cannot be caught at compile time. Pro: you don't have to have the
postgresql jar in the compile classpath, only the servers. Con: You have
to consider and write code for handling a ClassNotFoundException at
runtime.

If you wan't to handle it at compile time, look up the method
DriverManager.registerDriver(Driver driver). The driver calls this
itself when it is loaded, so it would be extra work without any good
effects besides that you no longer need to catch CLasNotFound but a
SQLException. :-)

Yours,
///Jens Carlberg

pgsql-jdbc by date:

Previous
From: Justin Clift
Date:
Subject: Re: Remember to register PostgreSQL for JDJ 2002 awards (fwd)
Next
From: "K. Ari Krupnikov"
Date:
Subject: Re: Problem with connecting to postgres using jdbc7.0-1.2.jar