2017-10-09 12 views
0

netbeans에서 데이터베이스에 액세스하려고하는데이 작업을 처음 수행 한 것입니다. finally 성명서를 읽었을 때 문제가 있습니다. ConnectionPrintWriter은 등록하지 않은 것 같아서 내가 잘못한 것을 잘 모릅니다. 문제는 try/catch에서 변수 con을 사용한 다음 변수 out을 사용하면 발생합니다.try/catch java에서 finally 문이 작동하지 않습니까?

import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.ResultSetMetaData; 
import java.sql.SQLException; 
import java.sql.Statement; 


@WebServlet(name = "DBServlet1", urlPatterns = {"/db1"}) 
public class DBServlet1 extends HttpServlet { 

/** 
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
* methods. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 
    //Connection con = null; 
    //PrintWriter out = response.getWriter(); 

    try (PrintWriter out = response.getWriter()) { 

     Connection con = null; 

     // Load the Driver class file 
     Class.forName("org.apache.derby.jdbc.ClientDriver"); 

     // Make a connection to the ODBC datasource Movie Catalog 
     // In this example we are opening a connection to the 
     // database with every request. 
     con = DriverManager.getConnection("jdbc:derby://localhost:1527/movies","user1", "password"); 

     if (con != null) { 
      out.println("<html>\n<body>\n<table border=\"1\" width=\"100%\">"); 
      // Create the statement 
      Statement statement = con.createStatement(); 
      ResultSet rs = statement.executeQuery("SELECT * FROM USER1.TMovie"); 
      ResultSetMetaData rsmd = rs.getMetaData(); 
      int columnCount = rsmd.getColumnCount(); 
      out.println("<tr>"); 

      for(int i=1; i<=columnCount; i++) { 
       out.println("<td><h3>" +rsmd.getColumnName(i) + "</td>"); 
      } 
      out.println("</tr>"); 

      while (rs.next()) { 
       out.println("<tr>"); 
       // get the id, which is an int 
       out.println("<td>" + rs.getInt("id") + "</td>"); 
       // get the name, which is a String 
       out.println("<td>" + rs.getString("title") + "</td>"); 
       // get the rating, which is a String 
       out.println("<td>" + rs.getString("rating") + "</td>"); 
       // get the price, which is a Float 
       out.println("<td>" + rs.getFloat("price") + "</td>"); 
       // get the Quantity, which is a Integer 
       out.println("<td>" + rs.getInt("quantity") + "</td>"); 
       // get the Category, which is a Integer 
       out.println("<td>" + rs.getString("category") + "</td>"); 
       out.println("</tr>"); 
      }// end while 
      // Close the ResultSet 
      rs.close(); 
      out.println("</table>"); 
     }// end if 
     else { 
      out.println("Data Not Found"); 
     } 
    }catch (Exception e) { 
     System.err.println(e.getMessage()); 
    }// end try-catch 
    finally { 
     try{ 
      if (con != null) { 
       // Close the connection no matter what 
       con.close(); 
      }// end if 
     } 
     catch (SQLException sqle) { 
      System.err.println(sqle.getMessage()); 
     }// end try-catch 
    }// end finally 
    out.close(); 

답변

2

Connection과 PrintWriter가 등록되지 않은 것 같아서 내가 잘못한 것을 잘 모릅니다.

그들은 모두 try 블록 내에서 을 선언하고 있습니다. 따라서 다른 모든 블록 범위 변수와 마찬가지로 해당 블록 외부에서는 액세스 할 수 없습니다. catch 또는 finally에 액세스해야하는 경우 try 외부에서 신고해야합니다.


사이드 참고 : 모든 자동 closeables위한 시도 -과 - 자원 문 (다만 PrintWriter), 예를 들어, 사용하는 경우 코드는 간단 할 것 연결 및 성명서와 함께; 그리고 올바르게 사용하면 (자원을 사용하여 시도한 것을 닫지 않아도됩니다.); tutorial. 내가 전체 코드 감사 또는 아무것도하지 않은

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 

    // Load the Driver class file 
    try { 
     Class.forName("org.apache.derby.jdbc.ClientDriver"); 
    } catch (Exception e) { 
     // *** Ideally, do something more useful with the exception or *don't* catch it 
     System.err.println(e.getMessage()); 
     return; 
    } 

    try (
     // *** Note all auto-closeables are created here 
     PrintWriter out = response.getWriter(); 
     // Make a connection to the ODBC datasource Movie Catalog 
     // In this example we are opening a connection to the 
     // database with every request. 
     Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/movies","user1", "password"); 
     // Create the statement 
     Statement statement = con.createStatement(); 
     ResultSet rs = statement.executeQuery("SELECT * FROM USER1.TMovie"); 
     ) { 

     out.println("<html>\n<body>\n<table border=\"1\" width=\"100%\">"); 
     ResultSetMetaData rsmd = rs.getMetaData(); 
     int columnCount = rsmd.getColumnCount(); 
     out.println("<tr>"); 

     for(int i=1; i<=columnCount; i++) { 
      out.println("<td><h3>" +rsmd.getColumnName(i) + "</td>"); 
     } 
     out.println("</tr>"); 

     while (rs.next()) { 
      out.println("<tr>"); 
      // get the id, which is an int 
      out.println("<td>" + rs.getInt("id") + "</td>"); 
      // get the name, which is a String 
      out.println("<td>" + rs.getString("title") + "</td>"); 
      // get the rating, which is a String 
      out.println("<td>" + rs.getString("rating") + "</td>"); 
      // get the price, which is a Float 
      out.println("<td>" + rs.getFloat("price") + "</td>"); 
      // get the Quantity, which is a Integer 
      out.println("<td>" + rs.getInt("quantity") + "</td>"); 
      // get the Category, which is a Integer 
      out.println("<td>" + rs.getString("category") + "</td>"); 
      out.println("</tr>"); 
     }// end while 
     // *** Don't close auto-closeables like the result set 
     out.println("</table>"); 
     /* *** This else was connected to an if (con != null), so the message doesn't really make sense 
     else { 
      out.println("Data Not Found"); 
     } 
     */ 
    } catch (Exception e) { 
     // *** Ideally, do something more useful here or don't catch the exception 
     System.err.println(e.getMessage()); 
    } 
    // *** No `finally` at all 
} 

, 나는 단지 자원의 사용에보고하고 관련 변화를 지적했습니다 여기

*** 의견주의 예입니다 올바르게 처리하십시오.

+0

감사합니다, 내가 어떤이 없습니다 오류 코드를 지금 조금 더 나은 이해가 있지만 여전히 db 값을 표시하지 않습니다 – Jaqtaris

+0

나는 DB에 대한 잘못된 주소를 모두 고정! 자세한 설명 주셔서 감사합니다 :) – Jaqtaris

1

변수 con 및 out의 범위가 올바르지 않습니다. try/catch/finally 블록 전에 선언해야합니다.

0

시도 -과 - 자원 블록 전에 변수를 선언 : -

Connection con = null;   
PrintWriter out =null, 

을 다음 쓰기 시도 -과 - 자원 블록을 다음과 같이 : -

try (out = response.getWriter()) { 
//here is your code