zim32
zim32

Reputation: 2619

Mysql JDBC driver ClassNotFoundException

I can't register Mysql JDBC driver in my desktop APP

I download mysql-connector-java-5.1.16.zip

Unzip mysql-connector-java-5.1.16-bin.jar and put it into lib folder in my app

Add this jar file into Build Path in Eclipse

But Class.forName("com.mysql.jdbc.Driver") throws ClassNotFoundException

Whats wrong?

enter image description here

Upvotes: 1

Views: 2630

Answers (3)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

In your lib directory,

  1. Right click the jar file that contains your driver.
  2. The go to Build-Path
  3. Choose Add to build path
  4. Run your code again

Also, if you are running JDBC 4.0 compatible driver you no longer need to automatically load your driver. According to JDBC 4.0 specification, section 3.1 under Automatic loading of java.sql.Driver says

DriverManager.getConnection has been modified to utilize the Java SE Service Provider mechanism to automatically load JDBC Drivers. This removes the need to invoke Class.forName.

Upvotes: 2

Tanner Perrien
Tanner Perrien

Reputation: 3133

  1. You could double check that the jar is really in the Eclipse build path.

    Project Properties > Java Build Path > Libraries > Add JARS
    
  2. Try a: Project > Clean on the Project menu in Eclipse.

Upvotes: 0

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

try this:

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
}

The issue is that Class.forName(String) throws an checked exception. With a checked exception, you can either:

  1. Catch the exception.
  2. Declare that your method throws the exception. (which is what I suggested above).

Here is an example of catching the exception:

public static void main(String[] args) throws Exception {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch(ClassNotFoundException e) {
        //do some exception handling
    }
}

Upvotes: 2

Related Questions