0

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());
    }
4
  • 2
    I don't want to be rude, but look into it. (here's a link anyway: mysql.com/downloads/connector/j ) Commented Aug 4, 2011 at 21:33
  • Jar file added without any success. Commented Aug 4, 2011 at 21:55
  • 2
    Done incorrectly. Believe what the JVM is telling you. Commented Aug 5, 2011 at 0:25
  • OK, this is interesting: 2K views, but 0 votes... Commented Aug 15, 2013 at 7:10

1 Answer 1

1

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

5
  • 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! Commented Aug 4, 2011 at 21:55
  • The first should not work. I referred to the lib directory of an application container. Commented Aug 4, 2011 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. Commented Aug 4, 2011 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. Commented Aug 5, 2011 at 0:25
  • I ended up getting this to work correctly. Thank you guys for the help Commented Aug 5, 2011 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.