0

I am trying to use an external mysql database in my java application, but I keep getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
when the application tries to make a connection.

This is the code I use to open the connection. What is causing this?

// Post: A connection is opened if the current connection is not valid
    private static boolean open() throws SQLException {
        // If connection is still valid, return without doing anything
        try {
            if (connection != null && connection.isValid(1)) {
                return true;
            }
        }
        catch (SQLException e1) {
            close();
        }

        // Start connecting
        String driver   = "com.mysql.jdbc.Driver";
        String url      = "jdbc:mysql://mysql.starredout.com/" + database;
        String user     = "starredout";     
        String password = "starredout";
        try {
            Class.forName(driver).newInstance();
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        connection  = DriverManager.getConnection(url,user,password);
        return true;
    }

    // Post: If a connection was open, it is closed
    private static void close() {
        try {
            if (connection == null || connection.isClosed())
                return;
            connection.close();
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }   
    }
0

3 Answers 3

2

The connector jar may not be on your classpath. If you are launching your application via the command line you should be able to manually add it by setting the classpath using the -classpath flag and following it with the path/to/the/jar/location.

If your code is running in a Java EE application server or the like the classpath becomes a little more complex and you will need to provide more details.

Sign up to request clarification or add additional context in comments.

Comments

1

That error means that it couldnt find the class you tried to make it run.
This is probably caused because you forgot to link the driver library to your build path?
The library is probably stored in a .jar file, so you have to mention that jar in your classpath.

In case you use eclipse just right click your project ==> Build path ==> configure build path, then click the Libraries tab, and click Add JARs... and select the jar you wish to include in the classpath In other IDE's it should be a similar process

Comments

0

You need to grab the mySql Connector jar and place it in your class path. You can take a look at the docs here

Comments

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.