选择查询无效。执行后直接转到Finally Block

时间:2014-09-04 11:17:56

标签: servlets jdbc select-query

这是我的代码。与数据库的连接正在运行。当语句posts = s.executeQuery(query)时;执行它甚至没有进入循环并从最后执行。不幸的是,没有异常抛出。

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
            + "Transitional//EN\">\n";
    String title = "Trend Blog";
    out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title
            + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=CENTER>" + title + "</H1>\n");
    Connection connection = null;
    ResultSet posts = null;
    ConnectMySql connectMySql = new ConnectMySql();
    String query = "select title,post from posts order by desc number";
    try {
        connection = connectMySql.getConnection("jdbc");
        Statement s = connection.createStatement();
        posts = s.executeQuery(query);
        int i = 1;
        while (posts.next()) {
            String postTitle = posts.getString(1);
            String post = posts.getString(2);

            HttpSession session = request.getSession();
            out.println("<h4>Welcome " + session.getAttribute("username")
                    + "</h4>");
            out.println("<p>");
            out.print("<h3><strong>" + i + "." + postTitle
                    + "</strong></h3>");
            out.println("<p>" + post + "</p>");
            out.print("</p><hr>");
            out.print("</body></html>");

        }

    } catch (SQLException e) {

    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您正在捕获第一个异常块,但是您不打印以查看它抛出的异常。

所以在你的第一个异常块中执行

} catch (SQLException e) {
  e.printStackTrace();

    } finally {
......

在第二个catch中,如果异常可能在第一个try-catch块中出现,则不会抛出任何异常。