moomin
moomin

Reputation: 43

Java Servlet & JDBC Driver Issue

Having a problem loading my driver from a test servlet, the error simply being

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Running the servlet via tomcat - which is running without issue as the localhost:8080 page is showing up in the browser. The servlet is attempting to connect to a database running in MySQL workbench.

Code within my servlet class, which attempts to load the driver:

        String driver = "com.mysql.jdbc.Driver";    
        Class.forName(driver).newInstance();
        // Make db connection
        con = DriverManager.getConnection(url, USERNAME, PASSWORD);   
        st  = con.createStatement();

System variables are setup as follows:

JAVA_HOME: C:\Program Files\Java\jdk1.7.0_02\

CLASSPATH: C:\apache-tomcat-6.0.35\lib\servlet-api.jar;C:\ProgramFiles\Java\jre7\lib\mysql-connector-java-5.1.22-bin;

PATH: C:\Program Files\Java\jdk1.7.0_02\bin

Now, as far as I can see, everything looks to be setup correctly. I would appreciate any input as to what may be causing the issue as I'm rather clueless as how else to troubleshoot this one.

Many thanks.

Upvotes: 2

Views: 2300

Answers (3)

BalusC
BalusC

Reputation: 1109625

The environment variable CLASSPATH is only used by java and javac commands in command console and even then only when you don't use any of the -cp, -classpath or -jar arguments. It's not been used during the runtime of a webapp deployed to Tomcat.

Instead, the webapp's default classpath covers among others the /WEB-INF/lib folder. You need to make sure that you drop the JDBC driver JAR(!) file in there (and definitely not the Servlet API JAR file!).

You should also not drop arbitrary JAR files in /lib or /lib/ext folders of the JRE. It would make your (web)applications unportable as they would not run in an environment which does not have the JDBC driver JAR file in the /lib folder of the JRE. In case of web applications, it really needs to be placed in /WEB-INF/lib folder so that it can be distributed as part of the webapp.


Unrelated to the concrete problem, the newInstance() call is superfluous on the MySQL JDBC driver. It's only necessary on the old MM driver which has a bug related to that. See also What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Upvotes: 2

asgoth
asgoth

Reputation: 35829

Your classpath for the MySql driver seems to be wrong:

Should be:

/path/mysql-connector-java-ver-bin.jar

More info

Upvotes: 0

Henry
Henry

Reputation: 43798

This part of the classpath is strange:

C:\ProgramFiles\Java\jre7\lib\mysql-connector-java-5.1.22-bin

I would have expected some jar file with the driver classes here.

Upvotes: 1

Related Questions