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());
    }
tier1
  • 6,303
  • 6
  • 44
  • 75

1 Answers1

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

Stefan Schubert-Peters
  • 5,419
  • 2
  • 20
  • 21
  • 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! – tier1 Aug 04 '11 at 21:55
  • The first should not work. I referred to the lib directory of an application container. – Stefan Schubert-Peters Aug 04 '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. – Stefan Schubert-Peters Aug 04 '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 05 '11 at 00:25
  • I ended up getting this to work correctly. Thank you guys for the help – tier1 Aug 05 '11 at 12:22