无法从Servlet建立数据库连接

时间:2015-07-31 09:03:44

标签: servlets jdbc

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.");
        }
    }
}

执行servlet后,我总是得到Exception

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

令人惊讶的是,当我执行DB.main()时,我可以毫无问题地建立连接。可能是什么问题?

我正在使用Eclipse / Apache Tomcat 8.代码被剪裁,但都是正确的。这个问题是关于servlet而不仅仅是Jav到MySQL。我的连接是成功的但不是servlet。

1 个答案:

答案 0 :(得分:1)

您需要将带有mysql JDBC驱动程序的JAR文件放入Webapp的WEB-INF/lib文件夹中,或放入Tomcat的lib文件夹中。