0

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;
}
4

2 回答 2

0

Technically you should not be closing your ResultSet but rather the database connection itself. This should not cause a memory leak provided you close your database connection when you have completed our database operations.

于 2012-09-05T19:38:30.927 回答
0

While you're closing the ResultSet, you're not closing the PreparedStatement statement that is associated with it. What you should be doing in your finally block is the following:

rs.getStatement().close();

This would ensure that the associated statement is closed. Also as per the Javadoc,

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

This means that when you close the statement object using the aforementioned code, you're also effectively closing the ResultSet object.

于 2012-09-06T05:18:24.380 回答