Does closing a java.sql.Connection
also close all the statements, prepared statements, etc. obtained from that connection? Or is there going to be memory leak if I close the connection but leave the statements, etc. unclosed?
At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects.
If the database sever grants all of them, and after their usage they are not closed, the database server would not be able to provide any other connection for another request. For that reason we need to close them - it is mandatory.
Yes it does, Connection. close API says "Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released".
You should explicitly close Statements , ResultSets , and Connections when you no longer need them, unless you declare them in a try -with-resources statement (available in JDK 7 and after). Connections to Derby are resources external to an application, and the garbage collector will not close them automatically.
Does closing a java.sql.Connection also close all the statements, prepared statements, etc. obtained from that connection? Or is there going to be memory leak if I close the connection but leave the statements, etc. unclosed?
You should not depend on it.
The spec reads as follows:
An application calls the method Statement.close to indicate that it has finished processing a statement. All Statement objects will be closed when the connection that created them is closed. However, it is good coding practice for applications to close statements as soon as they have finished processing them. This allows any external resources that the statement is using to be released immediately.
The best practice is to close ALL ResultSets, Statements, and Connections in a finally block, each enclosed in their own try/catch, in reverse order of acquisition.
Write a class like this:
public class DatabaseUtils
{
public static void close(Statement s)
{
try
{
if (s != null)
{
s.close();
}
}
catch (SQLException e)
{
// log or report in someway
e.printStackTrace();
}
}
// similar for ResultSet and Connection
}
Call like this:
Statement s;
try
{
// JDBC stuff here
}
finally
{
DatabaseUtils.close(s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With