Search code examples
javanetbeansnetbeans-8

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver if the project built into jar


I made my project use NetBeans, when I run it through NetBeans, it can run properly without any errors at all. But, when I build it into a jar file and try to login to my application, I get an error:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)

error1

And in cmd :

error

I have been do this tutorial and it not work. And I have been read and follow tutorial that was similar with this my problem in this website and others website, but nothing work for me.

this is my library : my library

And this is my code

 package config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
 *
 * @author nasution
 */
public class Koneksi {
    private static Connection koneksi;
    public static Statement stm;

    public static Connection getKoneksi() throws ClassNotFoundException{
        try{
            Class.forName("com.mysql.jdbc.Driver");
                koneksi = DriverManager.getConnection("jdbc:mysql://localhost/db_surat","root","");
        }catch(SQLException e){
            JOptionPane.showMessageDialog(null, "koneksi gagal"+ e.getMessage());
        }
        return koneksi;
    }

}

this is my project that has been converted to jar : project jar

and this is my library in folder "dist/lib" that was generated when I built the project my library


Solution

  • You need to declare required libraries in the /META-INF/MANIFEST.MF manifest file. If you look at Adding Classes to the JAR File's Classpath the syntax will be:

    Class-Path: lib/mysql-connector-java-5.1.23-bin.jar
    

    How will you modify the /META-INF/MANIFEST.MF depends on your JAR packaging mechanism, most of them give you an option to auto-generate this file.