转载

java – 最后关闭连接和语句

哪个更适合finally块:

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.

此外,如果您已经使用Java 7,则应考虑使用 try-with-resources ,它会自动关闭资源.从链接的教程:

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.

翻译自:https://stackoverflow.com/questions/18114905/close-connection-and-statement-finally

原文  https://codeday.me/bug/20190112/513113.html
正文到此结束
Loading...