Java-JDBC-MySQL Error

Posted by LeonardPeris on Ask Ubuntu See other posts from Ask Ubuntu or by LeonardPeris
Published on 2011-11-12T00:22:55Z Indexed on 2011/11/12 2:13 UTC
Read the original article Hit count: 590

Filed under:
|

I'm trying to get my java program to talk to a MySQL DB.

So i did some reading and downloaded MySQL Connector/J. I've extracted it into my home directory ~. Here are the contents.

user@hamster:~$ ls
LoadDriver.class  LoadDriver.java  mysql-connector-java-5.1.18-bin.jar

The contents of LoadDriver.java are

user@hamster:~$ cat LoadDriver.java 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

The contents are the same from http://dev.mysql.com/doc/refman/5.1/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-connect-drivermanager with the only change that the Exception is being printed to console in the catch block.

I compile it as follows

leonard@hamster:~$ javac LoadDriver.java

When I try to execute it, the following is the ouput.

leonard@hamster:~$ java LoadDriver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

This output is consistent with the executing command, but when trying to run it with the prescribed CLASSPATH method I run into the following issue.

leonard@hamster:~$ java -cp /home/leonard/mysql-connector-java-5.1.18-bin.jar LoadDriver
Exception in thread "main" java.lang.NoClassDefFoundError: LoadDriver
Caused by: java.lang.ClassNotFoundException: LoadDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: LoadDriver. Program will exit.

Am I missing something? How do I get MySQL's own code samples running.

© Ask Ubuntu or respective owner

Related posts about java

Related posts about mysql