0
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;

    //This class is for testing connection with mysql database 
    class JDBCTest {
    // path to database is stored in string url

        private static final String url = "jdbc:mysql://localhost";

    // username is stored  in string root

        private static final String user = "root"; //username

   // password is stored in string password 

       private static final String password = "swapnil";//password

        public static void main(String args[]) {
            try {
//i have stored driver in c:\javap\
            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
                Connection con = DriverManager.getConnection(url, user, password);
                System.out.println("Success");

            } catch (Exception e) {
                System.out.println("hi");
                e.printStackTrace();
            }
        }
    }

whenever I try to run this program I get the exception
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I am using mysql database my operating system is windows 7 64 bit. I have included the mysql-connector-java-5.1.22-bin in jdk/jre/lib/ext I have also set up the CLASSPATH Environment variable but nothing work me out

4
  • You need to add jdbc mysql jar in your classpath. It contains the driver implementation. Commented Apr 10, 2013 at 12:49
  • check classpath in your test : System.out.println(System.getProperty("java.class.path")); Commented Apr 10, 2013 at 12:52
  • i have added System.out.println(System.getProperty("java.class.path")); Commented Apr 10, 2013 at 13:17
  • i have added this line System.out.println(System.getProperty("java.class.path"));in my sample code after setting the classpath =.;c:\javap\mysql-connector-java-5.1.22-bin.jar; in environment varialbles. but when i run the program i get the output "." (dot) Commented Apr 10, 2013 at 13:20

2 Answers 2

3

First of all, you should not put anything under the JDK's jre/lib/ext directory.

Instead, use the -cp option when launching your application, and make sure to have the jar of the driver (and not the bin directory) in the classpath:

java -cp mysql-xx.jar;... com.foo.bar.JDBCTest
Sign up to request clarification or add additional context in comments.

Comments

1

The URL is incomplete use:

private static final String url = "jdbc:mysql://localhost:3306/databasename";

also as @JB Nizet mentioned do not put jars in jdk's lib.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.