can't connect to mysql through eclipse - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

时间:2016-03-02 20:01:01

标签: java mysql jdbc

i've tried connecting my java servlet project in eclipse with my mysql server, and it gives me this error - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

now, i've downloaded the latest connector jdbc from the mysql website, and i've put it in my java class path, and turned on the option.

also, i did checked the Driver class really is exist in the jar i downloaded, and it was.

i checked in google for hours for this problem, and couldnt find the solution.

here's my code, hopfully you guys can help me

LoginServlet.java

package androidLogin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;




@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {


    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("GET METHOD");
        Connection con = DBConnectionHandler.getConnection();
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

DBConnectionHandler.java

    package androidLogin;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.mysql.jdbc.Connection;

public class DBConnectionHandler {

    Connection con = null;

    public static Connection getConnection() {
        Connection con = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
            con =(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/loginuser", "host", "13241234");//mysql database

            if(con!=null){
                System.out.println("connected successfully");
            }

        } catch (SQLException | ClassNotFoundException ex) {
            System.out.println(ex);
//            Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("not connected to database");
        }
        return con;
    }
}

please help guys, i'm really desperate.

1 个答案:

答案 0 :(得分:4)

如果您在Servlet或任何其他容器中运行tomcat,请确保mysql jar位于servlet容器类路径中

也查看这些答案:

ClassNotFoundException com.mysql.jdbc.Driver

classpath, eclipse and java.lang.ClassNotFoundException: com.mysql.jdbc.Driver