简体   繁体   中英

ClassNotFound Exception for “com.mysql.jdbc.Driver” even after adding mysql-con.jar file

I have already set the classpath to mysql-connector-java-5.0.8-bin.jar and compiled my class successfully. But when I run it I get:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

The code is:

import java.sql.*;

public class JdbcExample
{

    public static void main(String arg[])
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://loacalhost:3306/sample","root","root");
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select * from sample");
            while(rs.next())
            {
                System.out.println(rs.getString(1));
            }
            con.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Make sure you are "adding" the mysql-connector-java-5.1.42-bin.jar file to the classpath when starting your program (obviously it can be a different version number).

something like

java -cp .;mysql-connector-java-5.0.8-bin.jar JdbcExample

or

set CLASSPATH=...;mysql-connector-java-5.0.8-bin.jar
java JdbcExample

assuming:

  1. the JAR is in the current folder... if that works, consider putting the JAR in a 'central' place a use the complete path in above commands

  2. using Windows, otherwise the separator would be : instead of ;

  3. the class is in no package

for Ubuntu:

java -cp .:mysql-connector-java-5.0.8-bin.jar JdbcExample

Looks like more of a classpath issue. Try adding the jar manually to your project. I ran the same with mysql-connector-java-5.0.8.jar and I dont get this error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM