Question

im trying to connect to the database but im getting this error.

this is the code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JDBCInsertValues {

    public static void main(String[] args) throws Exception {

        Class.forName("com.mysqljdbc.Driver");
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/Drivers");

        PreparedStatement statement = conn.prepareStatement("SELECT * fom employee");
        ResultSet result = statement.executeQuery();
        while(result.next()){
            System.out.println(result.getString(1)+ " "+ result.getString(2));
        }
    }
}

and this is the error im getting.

run:

Exception in thread "main" java.lang.ClassNotFoundException: com.mysqljdbc.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:259)
    at JDBCInsertValues.main(JDBCInsertValues.java:14)

Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

i have driver located on projects library.

Était-ce utile?

La solution

the driver name seems to be wrong

try

Class.forName("com.mysql.jdbc.Driver").newInstance();

instead of

Class.forName("com.mysqljdbc.Driver");

Autres conseils

I think you are using ANT. If it is the problem may be you've missed to include mysql library in build.xml

I also found the same issue in my code. In your code you have to do following things:

  1. change the first line of code in main method to Class.forName("com.mysql.jdbc.Driver")
  2. Now extract the MySQL Connector/J file like mysql-connector-java-5.1.32.zip.
  3. You will have jar file mysql-connector-java-5.1.32-bin.jar in the folder mysql-connector- java-5.1.32 extracted at step 2
  4. Now right lick on your project, go to Build Path >> Configure build path >> Libraries tab >> Add External JARs >> select mysql-connector-java-5.1.32-bin.jar from the folder mysql-connector-java-5.1.32
  5. Refresh and run your project. I hope these steps will solve your problem
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top