2014-09-04 59 views
0

這是我的代碼。與數據庫的連接正在工作。當聲明posts = s.executeQuery(query);它甚至不會進入循環並從最後執行。不幸的是沒有拋出異常。選擇查詢不起作用。直接執行後直接執行finally塊

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

您正在捕獲第一個異常塊,但是您不打印以查看它拋出了什麼異常。

因此,在您第一次異常塊做的

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

    } finally { 
...... 

在第二catch,就不會拋出的任何異常,如果一個例外可能在第一try-catch塊已經occcured。

+0

感謝您的回覆。我發現了這個問題。它是查詢後的數字後面加desc。 – Lucky 2014-09-17 05:43:22