java - finally 语句在 try/catch java 中不起作用?

标签 java database netbeans try-catch-finally

我正在尝试访问 netbeans 中的数据库,这是我第一次这样做。当我到达 finally 语句时遇到问题。 ConnectionPrintWriter 似乎没有注册,我不确定我做错了什么。问题在于在 try/catch 中使用变量 con,然后在其后使用变量 out

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();

最佳答案

The Connection and the PrintWriter don't seem to register and I'm not sure what I have done wrong.

它们都在 try block 声明。因此,就像任何其他 block 范围变量一样,它们在该 block 之外不可访问。如果需要在 catchfinally 中访问它们,则需要在 try 之外声明它们。

<小时/>

旁注:如果您对所有自动关闭项(不仅仅是 PrintWriter)使用 try-with-resources 语句,代码会更简单,例如以及连接和语句;如果你正确使用它(你不会关闭在 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
}

尚未进行完整的代码审核或其他任何操作,我只是查看了资源的使用情况并指出了与正确处理它们相关的更改。

关于java - finally 语句在 try/catch java 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641622/

相关文章:

java - 是否可以在 IntelliJ IDEA 2016 调试器中一键将变量对象列表折叠到特定深度?

java - GradlecompileTestJava 在 gradle clean 构建期间失败

java - 当我刷新浏览器时看不到变化 - Java EE Web 应用程序。 + Glassfish 4 + Netbeans + Java 7 + Mac 操作系统-

java - 如何获取存储在数据库中的图像路径并将其设置为按钮

java - 支持数据库连接的系统设计

java - 当我运行程序时没有可用的类(class)?

jquery - NETBEANS 自定义代码折叠

java - 在命令提示符下运行 Java 程序

java - Lettuce:响应式(Reactive) API 的共享连接

sql - 无法将 vb.net 项目与 Access 号进行比较