最后关闭连接和语句 [英] Close connection and statement finally

查看:127
本文介绍了最后关闭连接和语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对finally块更好:

Which is better for finally block:

finally {
        try {
            con.close();
            stat.close();
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }

或:

finally {
        try {
            if (con != null) {
                con.close();
            }
            if (stat != null) {
                stat.close();
            }
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }


推荐答案

使用方法是第二个,因为如果在初始化 con stat 时抛出异常,它们不会被初始化,并且可以被初始化为 null 。在这种情况下,使用第一个代码将会抛出 NullPointerException

Better way to use is the 2nd one, because if an exception is thrown while initializing con or stat, they won't be initialized, and might be left initialized to null. In that case, using the 1st code will throw NullPointerException.

Java 7 ,则应考虑使用 try-with-resources ,它会自动关闭资源。从链接的教程:

Also, if you are already on Java 7, you should consider using try-with-resources, which automatically closes the resources. From the linked tutorial:


try-with-resources语句确保每个资源在语句结束时关闭。实现java.lang.AutoCloseable的任何对象(包括实现java.io.Closeable的所有对象)都可以用作资源。

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

这篇关于最后关闭连接和语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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