简体   繁体   English

发生异常时的JDBC连接管理器和Connection对象

[英]JDBC connection manager and Connection object in case of Exception

I've a jdbc postgresql app and I write the "standard" connection manager. 我有一个jdbc postgresql应用程序,我编写了“标准”连接管理器。 For each successful transaction, I close the statement object, and connection object. 对于每个成功的事务,我关闭语句对象和连接对象。 If one of SQLException or ClassNotFoundException occours, what happen to statement and connection object? 如果发生SQLExceptionClassNotFoundException之一,则语句和连接对象会发生什么? In catch block should I close this two object or not? 在catch块中,我是否应该关闭这两个对象? Something like: 就像是:

Connection conn = null;
PreparedStatement pstm = null;
try {
    conn = ConnectionManager.getConnection();
    pstm = conn.CreateStatement(statement);
    //set statement
    }catch (SqlException ex) {
        if(conn != null) {
            pstm.close();
            conn.close();
        }
        throw new MyException("error");
    }catch (ClassNotFoundException ex) {
        if(conn != null) {
            pstm.close();
            conn.close();
        }
        throw new MyException("error");
     }
}

in catch block should i close this two object or not? 在catch块中我是否应该关闭这两个对象?

No . 不行 Never close any object in catch block. 禁止关闭挡块中的任何物体。 To close any resource use finally{} block. 要关闭任何资源,请使用finally{}块。

You can put your connection and statement close statements in finally block to be sure that those are closed no matter whether there is an exception or not. 您可以将您的连接和语句close语句放在finally块中,以确保无论是否存在异常都将其关闭。 Finally is always exceuted when the try block exits. 当try块退出时,最后总是被执行。 You can try something like this: 您可以尝试如下操作:

Connection conn = null;
PreparedStatement pstm = null;
try {
    conn = ConnectionManager.getConnection();
    pstm = conn.CreateStatement(statement);
    //set statement
    }catch (SqlException ex) {
        throw new MyException("error");
    }catch (ClassNotFoundException ex) {
   
        throw new MyException("error");
     }finally {
        if(conn != null) {
         try {
            pstm.close();
            conn.close();
         } catch (SQLException e) {  
           // throw or log the exception;
         }

        }
    }
}

In your code resources are tried to be closed in several places, causes code duplication. 在您的代码资源中尝试在多个地方关闭,导致代码重复。

So you should use finally block to close resources like bellow: 因此,您应该使用finally块关闭类似下面的资源:

 finally {
    if (pstm != null) {
        try {
           pstm.close();
        } catch (SQLException e) { /* ignored */}
    }

    if (conn != null) {
       try {
          conn.close();
       } catch (SQLException e) { /* ignored */}
    }
 }

Because what ever things happens, finally block will be executed before the return of the method call. 因为无论发生什么事情, finally块都将在方法调用返回之前执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM