0
public class MyServlet extends HttpServlet {
    /*Fields are correct*/
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        Connection sqlCon = DB.getConnection();
        if (null == sqlCon) {
            System.out.println("Could not establish connection.");
            return;
        } else {
            System.out.println("Connection successful.");
        }
    }
}

public class DB {
    /*Fields are correct*/
    public static Connection getConnection() {
        try {
            Class.forName(JDBC_DRIVERS);
            sqlCon = DriverManager.getConnection(URL, USER, PASSWORD);

        } catch(ClassNotFoundException | SQLException cnfe) {
            System.out.println("Drivers Problem.: " + cnfe);
        }
        return sqlCon;
    }
    public static void main(String args[]) {
        Connection sqlCon = DB.getConnection();
        if (null == sqlCon) {
            System.out.println("Could not establish connection.");
            return;
        } else {
            System.out.println("Connection successful.");
        }
    }
}

After I execute servlet, I always get Exception

Drivers Problem.: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Could not establish connection.

Surprisingly when I execute DB.main() I could establish connection without any issue. What might be the problem?

I am using Eclipse/Apache Tomcat 8. Codes are clipped, but all correct. This question is about servlet not Jav to MySQL only.. My connections are successful but not with servlet.

Nilesh
  • 2,089
  • 3
  • 29
  • 53

1 Answers1

1

You need to put the JAR file with mysql JDBC driver either into the WEB-INF/lib folder of your webapp, or into the Tomcat's lib folder.

Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25