Closing a CallableStatement

12.3k views Asked by At
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.

2

There are 2 answers

2
MeBigFatGuy On

closing database objects should always be done in a finally block, so that they are closed regardless of whether an exception occurred or not.

Connection c = null;
CallableStatement cstmt = null;

try {
    conn = getAConnectionSomewhere();  
    cstmt = conn.prepareCall("{call XXX");
    cstmt.executeUpdate();
} finally {
    IOUtils.close(cstmt);
    IOUtils.close(conn);
}

here, i've taken the liberty to use IOUtils from commons-io

0
Basil Bourque On

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.