isank-a
isank-a

Reputation: 1675

class not found exception even after everything seems right

I am working on simple connection between Java and MySQL using MySQL Connector J on Windows 8.

Below is the code that i am trying to execute:

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

public class Version {

public static void main(String[] args) {

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost:3306/test";
    String user = "testuser";
    String password = "test623";

    try {
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT VERSION()");

        if (rs.next()) {
            System.out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}
}

Compile: javac Version.java (goes without error and generates class file)

Execute: java -cp "path to mysql connector java jar file" Version

Execution Result:

Exception in thread "main" java.lang.NoClassDefFoundError: Version
Caused by: java.lang.ClassNotFoundException: Version
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: Version.  Program will exit.

Any idea where am i wrong?

Upvotes: 1

Views: 136

Answers (1)

piet.t
piet.t

Reputation: 11911

You have to add the directory containing Version.class to the classpath as well as the mysql-connector-jar.

If you don't add a classpath-parameter to the invokation java will look for class-files in the current directory by default. If you add a classpath, java will only search the mentioned jar-files/directories for class files, current directory has to be explicitly included as .

Upvotes: 3

Related Questions