为什么数据库连接经常在使用后直接关闭,然后在finally块中使用null检查再次关闭,以防止重复关闭。使用finally块不就足够了吗?finally块将在任何情况下执行。
这里是Apache-Tomcat JNDI Datasource HOW-TO的官方示例。他们指出每种情况下都必须关闭连接。我想知道为什么在主try {}块末尾的关闭命令似乎是多余的,使用finally块不够吗?
这里是Apache-Tomcat JNDI Datasource HOW-TO的官方示例。他们指出每种情况下都必须关闭连接。我想知道为什么在主try {}块末尾的关闭命令似乎是多余的,使用finally块不够吗?
Connection conn = null;
Statement stmt = null; // Or PreparedStatement if needed
ResultSet rs = null;
try
{
conn = ... get connection from connection pool ...
stmt = conn.createStatement("select ...");
rs = stmt.executeQuery();
... iterate through the result set ...
rs.close ();
rs = null;
stmt.close ();
stmt = null;
conn.close (); // Return to connection pool
conn = null; // Make sure we don't close it twice
}
catch (SQLException e)
{
... deal with errors ...
}
finally
{
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null)
{
try
{
rs.close ();
}
catch (SQLException ignore)
{
}
rs = null;
}
if (stmt != null)
{
try
{
stmt.close ();
}
catch (SQLException ignore)
{
}
stmt = null;
}
if (conn != null)
{
try
{
conn.close ();
}
catch (SQLException ignore)
{
}
conn = null;
}
}
我想写得更短:
Connection conn = null;
Statement stmt = null; // Or PreparedStatement if needed
ResultSet rs = null;
try
{
conn = ... get connection from connection pool ...
stmt = conn.createStatement ("select ...");
rs = stmt.executeQuery();
... iterate through the result set ...
}
catch (SQLException e)
{
// ... deal with errors ...
}
finally
{
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
try
{
if (rs != null)
rs.close ();
if (stmt != null)
stmt.close ();
if (conn != null)
conn.close ();
}
catch (SQLException ignore)
{
}
}
try-with-resources
更简短 ;) 但是,这个例子似乎过于复杂了。 - Marvinrs.close()
抛出异常会怎么样?那么stmt
和conn
将不会被关闭。 - Can't TellStatement
会关闭所有相关的ResultSet
,关闭Connection
会关闭所有相关的Statement
...因此,你建议的finally
块中三分之二都是多余的。 - user207421