Closing a CallableStatement

Yohei Nishioka picture Yohei Nishioka · Feb 1, 2011 · Viewed 9k times · Source
public void XXX(){
    Connection conn = ~~;        
    CallableStatement cstmt = conn.prepareCall("{call XXX");
    cstmt.executeUpdate();
    cstmt.close();
}

All methods that CallableStatement is described in close() line by line by the method like the above-mentioned. Cannot how to do close() in each method by the automatic operation be done?

Does the method that can be achieved with java5 or java6 exist?

Please tell me a better expression, because, I'm Japanese.

Answer

Basil Bourque picture Basil Bourque · May 29, 2019

try-with-resources

The modern approach uses the try-with-resources feature added to Java 7. A “resource” here means any object of a class implementing the AutoCloseable interface with its single method close. See Oracle Tutorial.

The try-with-resources syntax inserts a pair of parentheses between the try and its curly braces. Inside those parens you declare and initialize your resource object(s). You can have more than one resource within those parens. Each resource is declared and initialized on a statement line. Each line ends in a semicolon like any Java statement though the last semicolon is optional.

try (
    Connection conn = myDataSource.getConnection() ;
    Callable cstmt = conn.prepareCall( sql ) ;
) {
    cstmt.executeUpdate() ;
} catch ( … ) {
    …
}

By the way, in Java 9 and later you can declare and initialize your resource object outside the parens, earlier in your code. In this case, just put the resource’s variable name inside the parens to have it automatically closed.

Notice that we need not bother with a finally. The try-with-resources will call close on any of the resources that were successfully instantiated even if an exception is thrown at some point. The resources are closed in the reverse order in which they were declared.