JAVAでのResultSet/Statementのクローズ
JAVAでDB接続をする際にに使用するResultSet/Statmentで
原因がよくわからないExceptionが発生するとおもいます。
それは、リソースの開放が失敗したときなどに発生します。
複数リソースを解放しようとして失敗する例として以下のような場合があります。
public void hoge() throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(“SELECT * FROM Foo”);
// Use resultSet
}
finally {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
connection.close();
}
}
何かしらの原因にてResultSetが閉じた状態になっていると思います。
ですので、既に閉じられているResultSetに対して
closeを実行している為例外が発生しています。
複数リソースを解放するための方法
public void hoge() throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(“SELECT * FROM Bar”);
// Use resultSet
}
finally {
try {
if (resultSet != null)
resultSet.close();
}
finally {
try {
if (statement != null)
statement.close();
}
finally {
connection.close();
}
}
}
}
private Connection getConnection() {
return null;
}
このようにすることで、ほとんどが例外を投げる
データベース接続などを解放するためにはfinallyを使ってると思います。
しかし、finallyを使ってストリームを閉じる、などとなると、それほど細心の注意は払いません)。また、リソースを使うコードがチェックあり例外(checked exception)を投げない場合にも、finallyを使うことを忘れがちです。
関連記事:

コメントはまだありません。