Tomcat Servlet和MySQL

时间:2013-09-16 17:11:52

标签: java mysql tomcat servlets xampp

我在Windows 8上使用XAMPP。我想要做的是从Servlet访问MySQL数据库。

我已将MySQL Connector J jar文件包含到/ xampp / tomcat / lib目录中,下面是我要编译和运行的代码

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mysql.jdbc.Driver;

public class Exercise7 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Servlet - MySQL</title></head>");
    out.println("<body>");

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "";

    try {
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT VERSION()");

        if (rs.next()) {
            out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
        /*Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);*/
        out.println("Can't connect");

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            /*Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);*/
            out.println("Can't connect");
        }
    }
    out.println("</body></html>");
}
}

当我访问页面时,我看到“无法连接”结果,这显然意味着servlet和mysql之间的连接存在问题,所以任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

将MySQL连接器J jar文件复制到“javaDirectory / jre / lib / ext”,上面的代码工作正常

然而,还有其他可能的解决方案,可能比这更好,但至少练习这很好,我想是的。