Is that code affecting the Performance or cause any memory leaks? Here PreparedStatement object is not closed and doesn’t have the reference to close. Any suggestion on this?
private ResultSet getEmpData(String query){
ResultSet rs = null;
try {
rs = connection.prepareStatement(query).executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public int getEmployeeSalary(){
ResultSet rs = null;
int salary = 0 ;
try {
rs = getEmpData("SELECT SALARY FROM EMP WHERE NAME ='SAM'");
while (rs.next()) {
salary = rs.getInt(1);
}
} catch (SQLException e) {
}finally{
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return salary;
}
While you’re closing the
ResultSet, you’re not closing thePreparedStatementstatement that is associated with it. What you should be doing in yourfinallyblock is the following:This would ensure that the associated statement is closed. Also as per the Javadoc,
This means that when you close the statement object using the aforementioned code, you’re also effectively closing the ResultSet object.