Andrew Q
Andrew Q

Reputation: 57

NoClassDefFoundError when the jar exists, specifically for mysql-connector-java-8.0.20.jar

I want to make sure I can connect to the MySQL server I have running locally with a simple Java class.

To test the connection I want to use the MysqlDataSource class that comes with the mysql-connector-java-8.0.20.jar

I'm on Ubuntu 18.04 LTS and have the jar located at:/usr/share/java/mysql-connector-java-8.0.20.jar.

Then I run the compiler command: $ javac -cp "/usr/share/java/mysql-connector-java-8.0.20.jar" App.java

Then: $ java App

And get the following output error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mysql/cj/jdbc/MysqlDataSource
        at App.main(App.java:15)...

Output of $ mysql --version: mysql Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using EditLine wrapper

This is all my App.java file contains:

import java.sql.Connection;
import java.sql.SQLException;

import com.mysql.cj.jdbc.MysqlDataSource;

public class App {
    public static void main(String[] args) {

        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("test");
        dataSource.setServerName("localhost");

        Connection conn;
        try {
            conn = dataSource.getConnection();
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }    
}```


Upvotes: 0

Views: 109

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201429

Instead of java App, you must specify a classpath to include the jar at runtime. Like,

java -cp "/usr/share/java/mysql-connector-java-8.0.20.jar:." App

Upvotes: 1

Related Questions