1

I have the following code in which i'm getting class not found exception of com. mysql.jdbc.Driver. what should i do ?

    try {
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dimple?zeroDateTimeBehavior=convertToNull", "root", "password");
        PreparedStatement ps = con.prepareStatement("Insert Into data Values(? ,? )");
        ps.setString(1, name);
        ps.setString(2, pass);
       int f =  ps.executeUpdate();
       if(f>0)
       {
           out.println("Successfuly inserted");
           RequestDispatcher rd = request.getRequestDispatcher("index.html");
           rd.forward(request, response);
       }
       else
           out.println("Not inserted");

    }
    catch(Exception e)
    {
        out.println(e);
    }
Dimple
  • 131
  • 1
  • 11

2 Answers2

1

The MySql jar library containing the class com.mysql.jdbc.Driver, must be in your classpath.

Look at here for downloadable MySql drivers :

MySql JDBC Drivers

Arnaud
  • 16,319
  • 3
  • 24
  • 39
  • +1 If you are using Eclipse or any IDE, It probably would be a good idea to include this JAR in your project's Build Path. Also , on a different note - It could be a better implementation to use character array for password, not string. SEE : http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords-in-java?lq=1#comment11134505_8881291 – Gyan Jan 15 '16 at 08:12
  • thanku soo much for the help.. – Dimple Jan 22 '16 at 08:28
0

You should first download and add the driver jar file to your project classpath and then load that class.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not import com.mysql.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
    }
}

After these steps, you can work with the driver as you already do.

More information:

frogatto
  • 26,401
  • 10
  • 73
  • 111