使用JSP和Servlet POST方法查询MySQL

时间:2013-04-09 01:14:54

标签: mysql jsp servlets

我不确定我是否正在尝试正确“打印”我的结果。我要做的是使用JSP接收变量,然后将其传递给servlet,在servlet中它将查询数据库,然后显示结果。我测试了在不同的java文件中查询我的数据库,我没有遇到任何麻烦。任何建议将不胜感激!

JSP文件:

<form method="post" action="HelloServlet"/>
Enter your name:<input name = "exName"/><br>

<input type = "submit" />
</form>

JAVA文件(servlet):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {

        //response.setContentType("text/html; charset=ISO-8859-1");
        PrintWriter out = response.getWriter();

        java.sql.Connection con = null;
        java.sql.PreparedStatement pst = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/masters";  
        String user = "christine";
        String password = "password";

        try{
            String exName = request.getParameter("exName");
            con = DriverManager.getConnection(url, user, password);  
            pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name ='"+exName+"';");
            rs = pst.executeQuery();  

            while (rs.next()){
                String name = rs.getString("description_txt");

                out.print(exName);
                out.print(name);
            }   
        }catch(SQLException ex){
        }finally {
            try {
                if (rs != null){
                    rs.close();
                }
                if (pst != null){
                    pst.close();
                }
                if (con != null){
                    con.close();
                }
            }catch(SQLException ex){
            }           
        }       
    }

1 个答案:

答案 0 :(得分:0)

您需要在代码中更改一些内容。

正如@BalusC所提到的那样,不要压制异常。使用out.println(ex);throw new ServletException(ex)向浏览器写入例外。这有助于您找到问题的原因。

Class.forName("com.mysql.jdbc.Driver");之前添加DriverManager.getConnection()

正如您已经在使用PreparedStatement一样使用

pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name =?");
pst.setString(1, exName);
rs = pst.executeQuery();