最后关闭连接和声明

Saj*_*jad 7 java connection finally jdbc try-catch

哪个更适合finally块:

finally {
        try {
            con.close();
            stat.close();
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

要么:

finally {
        try {
            if (con != null) {
                con.close();
            }
            if (stat != null) {
                stat.close();
            }
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 15

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

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

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


Xab*_*ter 7

他们都不够好.用这个:

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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为 closeQuietly(stat, con);

或者使用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++));
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


Dav*_*njo 5

从Java 7开始,您不再需要使用finallyl块来关闭Connection或Statement对象.相反,您可以使用名为"try-with-resources"的新功能.

首先,使用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();
}    
Run Code Online (Sandbox Code Playgroud)

这样做,您不必担心在finally块中明确关闭与数据库的链接,因为jvm会为您执行此操作.

有很好的编码....