Question

I have an JDBC utility class which hold the Resultset,Statement and Connection instances as global references.This class has basic two methods like 'execute'(has some parameters) and 'close' and inside execute, above instances are created and assigned and finally returns the created Resultset.

And the 'close' method closes all the opened connections for Resultset,Statement and Connections simply like this.

public void close() {

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
                sqlEx.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException sqlEx) {
                sqlEx.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
            }
        }
    }

And my client application I create an instance of utility and get the resultset like below.

ResultSet rs = dbutil.execute(strQuery,values);

and if I close the Resultset using rs.close and again using dbutil.close() in my client application,

  1. will it occur some connection leak or memory leaks?
  2. what will happen if I use only rs.close() in my client?
  3. Are there any possibilities for making connection leaks there?

thanks in advance

Was it helpful?

Solution

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

Calling the method close on a ResultSet object that is already closed is a no-op. Please check the Java doc for resultset.

OTHER TIPS

Invoking close() on a ResultSet object that has already been closed has no effect and gives no error.

If you only use rs.close() you will leak the statement and the connection, which depending on how long lived your application is and whether you create new instances of your dbutil class could cause a database error (for your application, or for others using the same database) due to reaching the maximum number of open cursors (due to un-closed statements) or maximum number of connections (due to un-closed connections).

If you're using Java 7 you should also consider having your dbutil class implement the java.lang.AutoCloseable interface. That enables you to use the 'try-with-resources' pattern if you have declared your dbutil instance as a local variable. Opening connections to the database is relatively slow though, so you should avoid closing and reopening them lots of times in your application unless you are using connection pooling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top