4

I wrote some code that connects to a PostgreSQL 9.4 DB via its latest JDBC4 driver. My understanding is that JDBC4 no longer needs the boilerplate "Class.forName("org.postgresql.Driver") driver registration line. Thus, I left it out. It worked fine.

I then put the same exact code in a servlet, added the postgreSQL JDBC jar to WebContent/WEB-INF/lib and it failed saying:

java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost/

When I add the Class.forName line, it then works fine.

Does anyone know why this JDBC4 driver needs Class.forName when put within a doGet() servlet method, but in a basic Java class it doesn't?

Thanks, TR

edit: Forgot to mention, I'm using Java 7.

Some updates:

It does appear that this is a fairly common issue in Tomcat. I've moved the JAR out of WEB-INF/lib per the suggestions from this, and other posts. Even with it in TOMCAT_HOME/lib I need to use Class.forName(). Sort of odd, I suppose it has something to do with the way Tomcat registers classes.

Found this post which is the exact issue with the mySQL JDBC driver rather than postgreSQL:

When is Class.forName needed when connecting to a database via JDBC in a web app?

Community
  • 1
  • 1
user164266
  • 65
  • 4
  • Are you loading the class org.postgresql.Driver using some other means in standalone Java program, like creating an object of it,or something else? – Manish Maheshwari Nov 29 '14 at 20:52
  • 1
    Interesting question, watching this. – Hobbyist Nov 29 '14 at 20:52
  • Hello Manish. No I'm not loading the class using any other means. I can post the code, but it is really just a DriverManager connect and disconnect, nothing special or fancy in either situation. – user164266 Nov 29 '14 at 20:55
  • 1
    It seems to be a common occurrence in Tomcat, not specific to PostgreSQL. Take a look if [this answer](http://stackoverflow.com/a/10795977/4125191) might help you. – RealSkeptic Nov 29 '14 at 21:11
  • 1
    don't put the jdbc driver in web-inf/lib, see http://stackoverflow.com/q/6981564/217324 – Nathan Hughes Nov 29 '14 at 21:19
  • 1
    The URL is okay. The test I'm running just does a SELECT VERSION(), I'm not hitting a user-defined DB, just the postgreSQL system db which doesn't need to be specified. You are right though in that normally you do need a DB after the host. – user164266 Nov 30 '14 at 00:20

1 Answers1

0

Thanks all for the help with this. I found the exact situation and answer in the Tomcat 7 documentation while learning how to setup a JNDI datasource:

http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html#DriverManager,_the_service_provider_mechanism_and_memory_leaks

In short, under these circumstances, you need to register the driver using Class.forName even if you are using JDBC4 on Tomcat 7.

Thanks everyone for pointing me in the right direction! TR

user164266
  • 65
  • 4