Java, ResultSet.close(), PreparedStatement.close() -- what for?

Ibolit picture Ibolit · Feb 2, 2011 · Viewed 9.4k times · Source

In my web-application, i make extensive use of a database.

I have an abstract servlet, from which all the servlets that need a database connection, inherit. That abstract servlet creates a database connection, calls the abstract method which must be overriden by the inheriting servlets to do their logic, and then closes the connection. I do not use connection pooling, because my application will have a very limited number of users and operations.

My question is, what's the worst that can happen if i don't ever close the ResultSets, PreparedStatements and Statements that my inheriting servlets create, if the Connections that create them are always closed?

Answer

Tom Anderson picture Tom Anderson · Feb 2, 2011

The javadoc for Statement#close() says:

Note:When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

So you don't need to worry about closing ResultSets, as long as you always close Statements in a timely manner.

The javadoc for Connection#close() does not make a corresponding guarantee, but it does say:

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

Which you might reasonably construe as implying that any statements will be closed. Looking at the open-source jTDS driver, and peeking into the driver for a well-known and expensive commercial database, i can see that they do exactly that.