2017-10-09 10 views
0

私はnetbeansでデータベースにアクセスしようとしていますが、これは初めてです。私はfinallyステートメントに着くと問題があります。 ConnectionPrintWriterは登録されていないようだし、私が間違ったことをしているか分からない。問題は、try/catchに変数conを使用し、その後に変数outを使用することで発生します。finallyステートメントはtry/catch Javaで動作しませんか?

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ためのtry-と資源のステートメントを使用した場合、コードは単純になります(だけでなく、PrintWriter)、例えば接続とステートメントも同様です。それを正しく使うと(try-with-resourcesで開いたものを閉じることはありません。 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

私はデータベースのすべての間違ったアドレスを持っていた!詳細な説明をいただきありがとうございます:) – Jaqtaris

1

変数conとoutの有効範囲が正しくありません。 try/catch/finallyブロックの前に宣言する必要があります。

0

のtry-とリソースブロックの前に変数を宣言します -

Connection con = null;   
PrintWriter out =null, 

して、このようなトライでリソースブロックを記述します - ありがとう

try (out = response.getWriter()) { 
//here is your code 
関連する問題