Java 最后关闭连接和语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18114905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Close connection and statement finally
提问by Sajad
Which is better for finally block:
哪个更适合 finally 块:
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();
}
}
采纳答案by Rohit Jain
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
.
更好的使用方法是第二个,因为如果在初始化con
or 时抛出异常stat
,它们将不会被初始化,并且可能会被初始化为null
。在这种情况下,使用第一个代码将抛出NullPointerException
.
Also, if you are already on Java 7, you should consider using try-with-resources
, which automatically closes the resources. From the linked tutorial:
此外,如果您已经在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.
try-with-resources 语句确保每个资源在语句结束时关闭。任何实现 java.lang.AutoCloseable 的对象,包括实现 java.io.Closeable 的所有对象,都可以用作资源。
回答by bas
If there is a possibility either is null
, you must check that. If the possibility does not exist, there is no valid reason to check for it.
如果有可能是null
,您必须检查。如果这种可能性不存在,就没有正当理由去检查它。
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();
}
}
回答by Barranka
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
块,只是为了确保con
和stat
对象都标记为垃圾收集:
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;
}
}
回答by Xabster
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);
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++));
}
}
}
回答by David Archanjo
As of Java 7, you don't need any more use the finallyl block to close a Connection or Statement object. Instead you can make use of the new features called 'try-with-resources'.
从 Java 7 开始,您不再需要使用 finallyl 块来关闭 Connection 或 Statement 对象。相反,您可以使用名为“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....
有很好的编码....