Hey stupid question but I'm having a hard time connecting my java program to a mysql database. Throwing an exception when I hit this line.

Class.forName(driverName).newInstance();

The driver name is com.mysql.jdbc.Driver. I've searched around a bit on google and found something about a mysql-connector.jar file that I'm apparently supposed to have but I really haven't looked into it yet. Thanks.

Entire code:

Connection connection = null;
    try
    {
        String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver 
        Class.forName(driverName).newInstance();

        String serverName = "*********";
        String database = "canteen_web3";
        String url = "jdbc:mysql://" + serverName + "/" + database;
        final String username = "*****";
        final String password = "******";
        connection = DriverManager.getConnection(url,username,password);
        System.out.println("Connected!");
    }

    catch(Exception ex)
    {
        throw new ICException(ex.getMessage());
    }
share|improve this question

2  
I don't want to be rude, but look into it. (here's a link anyway: mysql.com/downloads/connector/j ) – Binyamin Sharet Aug 4 '11 at 21:33
Jar file added without any success. – tkcsam Aug 4 '11 at 21:55
1  
Done incorrectly. Believe what the JVM is telling you. – duffymo Aug 5 '11 at 0:25
feedback

1 Answer

up vote 1 down vote accepted

Start your app with

java -classpath .:mysql-connector.jar MyClass

The colon separates two paths. The . is the directory you are in (and hopefully the class or the base package), the latter jar is the driver.

For further information refer to the various sources of documentation http://download.oracle.com/javase/1.5.0/docs/tooldocs/windows/classpath.html

share|improve this answer
I just did add the jar to my C:\Program Files\Java\jre and \jre\lib directories without any success. Also trying to run from the CMD produces the same result. Thanks for the quick reply! – tkcsam Aug 4 '11 at 21:55
The first should not work. I referred to the lib directory of an application container. – pvblivs Aug 4 '11 at 22:04
If you set the classpath you have to set the path of the actual class as well. I forgot that and updated my answer. – pvblivs Aug 4 '11 at 22:15
+1 - this is the only correct answer. You already have the evidence that your solution doesn't work, because the class loader never found that JAR. Believe what the JVM is telling you. – duffymo Aug 5 '11 at 0:25
I ended up getting this to work correctly. Thank you guys for the help – tkcsam Aug 5 '11 at 12:22
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.