2

I am using Java/Eclipse to connect to MySQL database but encountering the following error.

Error Message:

Unable to connect to databasejava.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Code:

<%
  try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection myCon = DriverManager.getConnection("jdbc:mysql://localhost/myDB", "root", "password");
    if(! myCon.isClosed())
      out.println("Successfully connected to " + "MySQL server!");

    myCon.close();
  }catch(Exception ex){
      out.println("Unable to connect to database" + ex);
  }      
%>

I know that this question has already been asked here but still I am unable to sort this thing out.

Environmental variables:

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

CLASSPATH: .%JAVA_HOME%\lib;C:\Program Files\MySQL\Connector J 5.1.29;

How can I can solve this issue?

Community
  • 1
  • 1
Warrio
  • 1,853
  • 4
  • 28
  • 45
  • As @ThorbjørnRavnAndersen said, the CLASSPATH generally won't apply in a web environment. Even if it did (in more classic environment), you'd need the exact jar name, not the name of the directory containing the jars. – Bruno Mar 29 '14 at 15:00
  • @bruno see http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/classpath.html for instructions on how to use wildcards in the Classpath definition. – Thorbjørn Ravn Andersen Mar 30 '14 at 12:47

4 Answers4

6

The Eclipse project doesn't know where you have the drivers for the database. You need to include them under the WEB-INF/lib directory so that they become part of the classpath.

Alan
  • 822
  • 1
  • 16
  • 39
2

Inside tomcat the external definitions do not apply.

Either deploy the driver jar with your application or add it to the extension library inside Tomcat. I would use the first if Tomcat is not expected to help you with e.g. connection pools or similar

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
1

if you are using eclipse then add MySQL jars in projects lib folder.

coreJavare
  • 1,409
  • 2
  • 10
  • 21
  • Thank you for all these answers. It worked after copying mysql-connector-java-5.1.29-bin.jar to WEB-INF/lib directory. Is't there another way by adding a code statement that will reference the mySql connector jar? In a forum, they suggested to write the following: java -cp;. myclass Where am I supposed to write this command? Thank you again. – Warrio Mar 29 '14 at 15:12
0

Yes it worked for me also for the error as java.lang.ClassNotFoundException: com.mysql.jdbc.Driver.

Copied the sql connector jar file to lib folder of web-inf .

After copying this, the value from html to mysql database is sucessfully inserted Thanks for the Help