Quan Phung
Quan Phung

Reputation: 9

Java jdbc handle close connection

I have two question for my problem .

1.Is it necessary to include a catch block in my method if I have a throw?

2.Is it necessary to try - finally block in my method to handle connection.close?

public int count() throws SQLException {
    XAConnection xaConnection=null;
    Statement statement=null;
    ResultSet resultSet=null;
    int count  =0;
    try{
      String SQL = "SELECT count(*) FROM book";
      xaConnection = dbService.getConnection();
      statement = xaConnection.getConnection().createStatement();
      resultSet = statement.executeQuery(SQL);
      if(resultSet.next()){
        count = resultSet.getInt(1);
      }
    }
    finally {
      if(xaConnection!= null){
        xaConnection.close();
      }
      if(resultSet != null){
        resultSet.close();
      }
      if(statement != null){
        statement.close();
      }
    }
    return  count;
  }

Upvotes: 0

Views: 205

Answers (1)

Kaan
Kaan

Reputation: 5754

1. Is it necessary to include a catch block in my method if I have a throw?

No, it's fine to do try-finally. Allowed combinations include try-catch, try-finally, and try-catch-finally.

There's also an option called "try with resources" which looks like a standalone "try" but behind the scenes it behaves like try-finally. There are some examples in the Java Language Spec section 14.20.3.1.

2. Is it necessary to try - finally block in my method to handle connection.close?

No, it isn't strictly necessary – Java will allow you to do it. However, opening connections without closing them will lead to problems over time, so yes you should close them.


Here's an edit to your posted code showing how you could clean things up by using try-with-resources.

  • There's an outer try-finally where xaConnection is closed – it isn't possible to do try-with on javax.sql.XAConnection because it doesn't implement java.lang.AutoCloseable.
  • Statement and ResultSet both work with AutoCloseable, so they're inside try-with-resources blocks.
  • Removed the "count" variable – if you find a value in the result set, just return it; otherwise return 0 (like you were doing)
import javax.sql.XAConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public int count() throws SQLException {
    String SQL = "SELECT count(*) FROM book";
    XAConnection xaConnection = dbService.getConnection();
    try {
        try (Statement statement = xaConnection.getConnection().createStatement()) {
            try (ResultSet resultSet = statement.executeQuery(SQL)) {
                if (resultSet.next()) {
                    return resultSet.getInt(1);
                }
            }
        }
        return 0;
    } finally {
        if (xaConnection != null) {
            xaConnection.close();
        }
    }
}

Upvotes: 2

Related Questions