爲什麼數據庫連接通常在兩個位置關閉,一次是在使用後直接關閉,另一個是在finally塊中使用檢查null以防止它們關閉兩次。使用finally塊不夠嗎? finally塊將在每種情況下執行。僅在finally塊中關閉JDBC連接?
這是Apache-Tomcat JNDI Datasource HOW-TO的官方示例。他們指出,在任何情況下都必須關閉連接。我想知道爲什麼僅僅使用finally-block是不夠的,因爲主try {}塊結尾的close命令似乎是重複的。
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)
{
}
}
這是我第一次看到這個。我遇到的所有示例都只在finally塊中進行。我不認爲這是一種非常流行的做法。我認爲它增加了代碼的開銷和複雜性。 –
甚至更短的'嘗試與資源';)但是,這個例子似乎過於複雜。 – Marvin
如果rs.close()在您的代碼中引發異常,該怎麼辦?然後'stmt'和'conn'不會被關閉。 –