Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
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 docs.oracle.com/javase/7/docs/technotes/tools/solaris/… for instructions on how to use wildcards in the Classpath definition. –  Thorbjørn Ravn Andersen Mar 30 '14 at 12:47

3 Answers 3

up vote 5 down vote accepted

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.

share|improve this answer

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

share|improve this answer

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

share|improve this answer
    
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<path to jars>;. myclass Where am I supposed to write this command? Thank you again. –  Warrio Mar 29 '14 at 15:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.