为什么JDBC连接需要在finally块中关闭?

Ran*_*ddy 4 java jdbc

Connection conn = null;
Statement stmt = null; 
ResultSet rs = null;
try
{
    conn = geting the connection object ( using DriverManager.getConnection() method or using connection pool)
    stmt = conn.createStatement ("select ...");
   // some other logic here
}
catch (SQLException e)
{
    // handling the exceptions
}
finally
{

}
Run Code Online (Sandbox Code Playgroud)

这里我的问题是在以下情况下关闭连接对象时会出现什么问题.

  1. 假设没有发生异常,在try块中它会自动关闭连接对象.

    try {
         // same above code 
         stmt.close();
         conn.close();
    } catch(Exception ex) {
        // handling the exceptions
    } finally {
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果发生了一些异常,那么它将进入catch块,它会自动关闭连接对象.

    try {
         // same above code 
    
    } catch(Exception ex) {
        // handling the exceptions
        stmt.close();
        conn.close();
    } finally {
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 关闭finally块中的连接对象.

    try {
         // same above code 
    
    } catch(Exception ex) {
        // handling the exceptions
    
    } finally {
        stmt.close();
        conn.close();
    } 
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用close()方法关闭连接对象和使用close()关闭池连接之间的区别.

注意:请不要说在finally块中关闭连接对象是好的.我知道那个.如果我在try块中保持密切连接,catch块是否有任何问题请解释.

Bac*_*ash 13

建议关闭finally块中的连接,因为如果你有多个catch块(你应该这样做:你永远不应该删除泛型Exception),你就不必重新编写结束语句.

一个finally块将总是后执行try,无论发生什么事情.因此,如果您获得了一个NullPointerException或者您没有处理的其他异常,那么使用该finally块您将确保正确关闭您的资源.

但如果您使用的是java 7,我建议使用try-with-resources


小智 7

由于数据库消耗的资源越来越多,因此建议您在处理完成后关闭连接,无论是否成功.

你说,加上conn.close()try,这是好的,如果您的查询运行没有任何异常,如果你的查询有任何问题,该连接不会被关闭.所以总是建议在finally块中关闭你的连接,无论是否发生异常,都会执行.此外,如果您尝试将结束语句放在catch块中并尝试处理多个异常,则需要重复您不建议使用的代码.