Take a look at this simple database query method that is giving me the warning Resource Leak: 'ps' may not be closed at this location
in the return line..
public Bancos getDefault() {
Debug.out("");
PreparedStatement ps = null;
Bancos banco = null;
try {
String query = "SELECT * FROM " + TABLE_BANCOS + " " +
"WHERE " + FIELD_KEY + " = ?;";
ps = connector.prepareStatement(query);
ps.setString(1, new ParametrosManager().getParametros().getCodigoBanco());
ResultSet rs = ps.executeQuery();
if(rs.next()) {
banco = new Bancos(
rs.getString(FIELD_KEY),
rs.getDate(FIELD_DATAREGISTO),
rs.getString(FIELD_ABREVIATURA),
}
rs.close();
ps.close();
} catch(SQLException se) {
se.printStackTrace();
} finally {
try {
if(ps != null)
ps.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
return banco;
}
I wonder why eclipse gives me this warning since I'm even closing ps
on a finally
block. Would this be just a false positive warning?
I use Java 7.
SOLUTION:
It seems to be a problem with Java 7, check this answer from the duplicate question.
So, the fixed code:
public Bancos getDefault() {
Debug.out("");
Bancos banco = null;
String query = "SELECT * FROM " + TABLE_BANCOS + " " +
"WHERE " + FIELD_KEY + " = ?;";
try( PreparedStatement ps = connector.prepareStatement(query); ) {
ps.setString(1, new ParametrosManager().getParametros().getCodigoBanco());
ResultSet rs = ps.executeQuery();
if(rs.next()) {
banco = new Bancos(
rs.getString(FIELD_KEY),
rs.getDate(FIELD_DATAREGISTO),
rs.getString(FIELD_ABREVIATURA),
}
rs.close();
} catch(SQLException se) {
se.printStackTrace();
}
return banco;
}
My thanks to Luiggi for pointing me to the answer.