开发者

ClassNotFoundException when trying to use mysql in java

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());
        }   
    }


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜