简体   繁体   English

最终关闭连接并声明

[英]Close connection and statement finally

Which is better for finally block: 最终屏蔽哪个更好:

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

Or: 要么:

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

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 . 更好的使用方法是第二种,因为如果在初始化constat引发异常,则不会对其进行初始化,并且可能会将其初始化为null In that case, using the 1st code will throw NullPointerException . 在这种情况下,使用第一个代码将抛出NullPointerException

Also, if you are already on Java 7 , you should consider using try-with-resources , which automatically closes the resources. 另外,如果您已经在使用Java 7 ,则应考虑使用try-with-resources ,它会自动关闭资源。 From the linked tutorial: 从链接的教程中:

The try-with-resources statement ensures that each resource is closed at the end of the statement. try-with-resources语句可确保在语句末尾关闭每个资源。 Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. 任何实现java.lang.AutoCloseable的对象(包括所有实现java.io.Closeable的对象)都可以用作资源。

None of them are good enough. 他们都不够好。 Use this: 用这个:

public static void closeQuietly(AutoCloseable ... closeables) {
    for (AutoCloseable c : closeables) {
        if (c != null) {
            try {
                c.close();
            } catch (Exception e) {
                // log or ignore, we can't do anything about it really
            }
        }
    }
}

And call it like closeQuietly(stat, con); 并像closeQuietly(stat, con);这样称呼它closeQuietly(stat, con);

Or use java 7's try-with-resource : 或使用Java 7的try-with-resource

    List<String> results = new ArrayList<>();
    try (Statement statement = conn.createStatement();
         ResultSet rs = statement.executeQuery(query)) {

        int numberOfColumns = getColumnCount(rs);
        while (rs.next()) {
            int i = 1;
            while (i <= numberOfColumns) {
                results.add(rs.getString(i++));
            }
        }
    }

As of Java 7, you don't need any more use the finallyl block to close a Connection or Statement object. 从Java 7开始,您不再需要使用finallyl块来关闭Connection或Statement对象。 Instead you can make use of the new features called 'try-with-resources'. 相反,您可以使用称为“ try-with-resources”的新功能。

First you declare a Connection and Statament objects by using the new syntax for a try-catch block as follows: 首先,使用try-catch块的新语法声明一个Connection和Statament对象,如下所示:

try(Connection con =  DriverManager.getConnection(database-url, user, password); Statement st = conn.createStatement()) {

 //your stuffs here
} catch (SQLException e) {
   e.printStackTrace();
}    

Doing so, you won't need to worry to close explicitly the linkage with the database in a finally block because the jvm will do it for you. 这样做,您不必担心在finally块中显式关闭与数据库的链接,因为jvm会为您完成。

Have nice coding.... 编码不错。

If there is a possibility either is null , you must check that. 如果有可能为null ,则必须检查。 If the possibility does not exist, there is no valid reason to check for it. 如果可能性不存在,则没有正当理由进行检查。

Also, you can make your code slightly better readable by omitting some single-statement brackets: 另外,您可以通过省略一些单语句括弧来使代码的可读性更好:

finally {
    try {
        if (con != null)
            con.close();

        if (stat != null)
            stat.close();

    } catch (SQLException sqlee) {
        sqlee.printStackTrace();
    }
}

I would go with the second option, but adding a second nested finally block, just to make sure that both con and stat objects are marked for garbage collection: 我会选择第二个选项,但是要添加第二个嵌套的finally块,以确保将constat对象都标记为垃圾回收:

finally {
    try {
        if(con != null)
            con.close();
        if(stat != null)
            stat.close();
    } catch(SQLException sqlee) {
        sqlee.printStackTrace();
    } finally {  // Just to make sure that both con and stat are "garbage collected"
        con = null;
        stat = null;
    }
}

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

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