如何在while循环中正确处理Connection,ResultSet和Statement对象 [英] How to properly dispose of Connection, ResultSet, and Statement objects in a while loop

查看:159
本文介绍了如何在while循环中正确处理Connection,ResultSet和Statement对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码,这将是关闭Connection,ResultSet和Statement对象的正确方法吗?我觉得对close()的所有调用都应该在finally块中.

If i have the following code would this be the correct way of closing the Connection, ResultSet, and Statement objects? I feel like all of the calls to close() should be in a finally block.

Connection con = null;
ResultSet rs = null;
Statement stmt = null;

try{
    //Code before the while loop 
    con = DriveManager.getConnection("Stuff");

    while(someBoolean){          

        stmt = con.createStatement();
        rs = stmt.executeQuery("SQL query");

        // do stuff with query results.

        if( rs != null){
               rs.close();
        }

        if( stmt != null){
               stmt.close();
        }

} //end while

    if( con != null ){
        con.close();
    }

catch (Exception e){
    //handle exception
}

推荐答案

您无需在循环中创建Statement:您可以重复使用它.同样,对于Java 7 try-with-resources(教程),您也可以不需要按正确的顺序处理繁琐的工作,等等.

You don't need to create the Statement in the loop: you can re-use it. Also with Java 7 try-with-resources (tutorial) you don't need to take care of the tedium of closing in the right order, etc.

您可以这样做:

try (
    Connection con = DriverManager.getConnection("Stuff");
    Statement stmt = con.createStatement();
){
    while(someBoolean){          
        try (ResultSet rs = stmt.executeQuery("SQL query")) {
            // do stuff with query results.
        }
    } //end while
} catch (Exception e){
    //handle exception
}

正如您所看到的,它需要比自己管理少得多的检查和语句,尽管它确保了按正确的顺序关闭资源,即使发生异常(即使在关闭其他资源之一时也发生了异常).例如,如果发生任何异常,您的旧代码无法关闭资源.

As you can see it requires a lot less checks and statements than managing it yourself, while it ensures closing the resources in the right order, even if exceptions occur (even if that exception occurs when closing one of the other resources). For example your old code failed to close resources if any exception occurred.

这篇关于如何在while循环中正确处理Connection,ResultSet和Statement对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆