Force proper disposal of resultsets and statements

This commit is contained in:
Marco Cunha 2012-10-22 15:03:31 +02:00
parent 34ae64706e
commit 896f57f0b4

View File

@ -138,7 +138,7 @@ public class Database {
*/ */
public void checkDatabaseStructure(DatabaseUpdate update) { public void checkDatabaseStructure(DatabaseUpdate update) {
String sql = null; String sql = null;
ResultSet resultSet; ResultSet resultSet = null;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>(); HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
switch (update) { switch (update) {
@ -154,8 +154,9 @@ public class Database {
break; break;
} }
PreparedStatement statement = null;
try { try {
PreparedStatement statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
@ -167,8 +168,6 @@ public class Database {
rows.put(resultSet.getRow(), column); rows.put(resultSet.getRow(), column);
} }
statement.close();
} }
catch (SQLException ex) { catch (SQLException ex) {
switch (update) { switch (update) {
@ -186,6 +185,21 @@ public class Database {
default: default:
break; break;
} }
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// Ignore the error, we're leaving
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// Ignore the error, we're leaving
}
}
} }
} }
@ -197,15 +211,24 @@ public class Database {
*/ */
public boolean write(String sql) { public boolean write(String sql) {
if (checkConnected()) { if (checkConnected()) {
PreparedStatement statement = null;
try { try {
PreparedStatement statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.executeUpdate(); statement.executeUpdate();
statement.close();
return true; return true;
} }
catch (SQLException ex) { catch (SQLException ex) {
printErrors(ex); printErrors(ex);
return false; return false;
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
printErrors(ex);
return false;
}
}
} }
} }