除了特定問題/問題,這是壞練習宣佈昂貴的和外部的資源,如Connection
,Statement
和ResultSet
作爲一個實例變量,更不用說作爲static
變量。這些資源沒有無窮無盡的生命週期,當DB決定超時連接時,應用程序可能會中斷,因爲它在使用後沒有被釋放回數據庫。
我無法想象它在C#中的做法是不同的(它也是應用程序中的一個bug),但是正常的JDBC成語是您在儘可能短的範圍內獲取並關閉它,同樣的方法塊。例如。
public Entity find(Long id) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
Entity entity = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_FIND);
statement.setLong(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()) {
entity = new Entity();
entity.setProperty(resultSet.getObject("columnname"));
// etc..
}
} finally {
// Always free resources in reversed order.
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return entity;
}
的database.getConnection()
可以但是在技術上完全可以做靜態這樣的:
public final class Database {
static {
try {
Class.forName("com.example.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
private Database() {
// No need to instantiate this class.
}
public static Connection getConnection() {
DriverManager.getConnection("jdbc:example://localhost/dbname", "user", "pass");
}
}
,這樣你可以使用它作爲
connection = Database.getConnection();
(你還真需要關閉的finally
block after use!)
但是,這使得t他的連線源也真的是static。您不能再利用多態性和/或繼承來切換連接源(如連接池)(以獲得更好的性能)。爲了獲得更多想法/見解,您可能會發現this article有用
爲什麼我需要'final'修飾符? – Pentium10
@ Pentium10:防止類被擴展;如果它可以被擴展,那麼它可以被實例化。 –