Servlet Throws Exception at Runtime in Eclipse

Whenever I run my servlet in eclipse it shows:

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

I already connect the jar file properly and set the path in build path config. Is there anything else I can do?

Uninstall and re-install MySQL?

{
    [...]
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection
        ("jdbc:mysql://localhost:3306/example","root","root");
    String qr="select * from details where name=? and pwd=?";
    PreparedStatement ps=con.prepareStatement(qr);
    ps.setString(1, name);
    ps.setString(2, pwd);

    ResultSet rs=ps.executeQuery();
    if(rs.next())
    {
        out.println("home");
    }
    else
    {
        out.println("Invalid name and password");
    }
    con.close();
} catch(Exception e) {
    out.println(e);
}

I expect the output "home" or "invalid name and password"

Upvotes: 0

Views: 24

Answers (1)

Stephen C
Stephen C

Reputation: 718718

Uninstall and re-install MySQL?

No. The problem is in your Java client code, not the MySQL installation.

You should no longer do this:

 Class.forName("com.mysql.jdbc.Driver");

The correct way is to just call:

 Connection con = DriverManager.getConnection(url, user, password);

with the correct JDBC url, username and password.

This is the correct way to use DriverManager for any JDBC 4.0+ compliant driver; see javadoc. The DriverManager class initialization will use the service provider mechanism to find and load the actual driver class.

The most likely reason your code doesn't work is that the fully qualified classname of the Driver class has changed in Connector/J 8.0. Basically, your code is asking the JVM to load a class that no longer exists.

If this doesn't explain / fix your problem (i.e. you are using Connector/J 5.1 or earlier), then the most likely explanation is that the you don't have the driver JAR file on the above code's runtime classpath. But the code change is advisable anyway.

Upvotes: 1

Related Questions