class not found exception com.mysql.jdbc.driver even I added the jar file

2.4k Views Asked by At

Sory for my weak english, I want to connect mysql connection with java, I added the mysql-connector.jar but class not found error still continue. Here is the screenshot of build path.

What should I do for the connect mysql

enter image description here

Here is the code

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


try{


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

                conn = DriverManager.getConnection(DB_URL,USER,PASS);


                String sql1 = "INSERT INTO test (name) VALUES(?)";
                stmt = conn.prepareStatement(sql1);

                stmt.setString(1, okey);
                }

              // execute insert SQL stetement
                stmt .executeUpdate();


                stmt.close();
              conn.close();
           }catch(SQLException se){
              //Handle errors for JDBC

              se.printStackTrace();
           }catch(Exception e){
              //Handle errors for Class.forName
              e.printStackTrace();

           }finally{

              try{
                 if(stmt!=null)
                    stmt.close();
              }catch(SQLException se2){
              }// nothing we can do
              try{
                 if(conn!=null)
                    conn.close();
              }catch(SQLException se){

              }//end finally try
           }//end try
2

There are 2 best solutions below

4
On

I don't know what IDE you are using there, but... are you sure you shouldn't have added the connector jar under 'Libraries' instead of 'Order and Export'? Also, is the connector jar available to your deployed application (server container, EJB server, whatever) and not just available to you IDE?

Strictly speaking you probably don't need the connector jar to be known to your IDE: it will know about the JDBC interfaces and classes from java.sql.* (assuming you have configured it to know about the JDK it is to use) and that is all it should need to be able to compile your JDBC code. However, at runtime your application will need the classes from the connector jar available. How you achieve this depends in what kind of application you are building (standalone, webapp etc) and where you are deploying it (webserver, EJB container, etc).

3
On

Putting the connector jar file in the "WEB-INF/lib" folder will work.