commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dirk Verbeeck <dirk.verbe...@pandora.be>
Subject Re: [DBCP] getNumActive() returns a negative value
Date Tue, 02 Sep 2003 21:26:21 GMT
The advantage of closing your connection in the try block is that you 
can respond to SQLExceptions but I agree it is a lot of code.

This is also a nice way to write jdbc code:
try {
  Connection conn = getConnection();
  try {
    Statement stmt = conn.createStatement();
    try {
      ResultSet rs = stmt.executeQuery("select ...");
      try {
        // ... iterate through the result set ...
      } finally {
        rs.close();
      }
    } finally {
      stmt.close();
    }
  } finally {
    conn.close();
  }
} catch (SQLException e) {
  // ... deal with errors ...
}

Not an improvement you say, not in this form but look at it this way:

  private void updateStuff() {
    try {
      Connection conn = getConnection();
      try {
        lookupStuff(conn);
        // ... do more stuff in the same connection/transaction
      } finally {
        conn.close();
      }
    } catch (SQLException e) {
      // ... deal with errors ...
    }
  }

  private void lookupStuff(Connection conn) throws SQLException {
    PreparedStatement stmt = conn.prepareStatement("select ...");
    try {
      ResultSet rs = stmt.executeQuery();
      try {
        // ... iterate through the result set ...
      } finally {
        rs.close();
      }
    } finally {
      stmt.close();
    }
  }

But there are 101 ways to write sql java code...


Cheers
Dirk



jbisotti@lexmark.com wrote:

> Aitor,
>
> Below, I've copied the code listing from the Tomcat How-To. Notice, if all
> goes well, the connection is closed and set to null in the try block. If
> that's the case, the 'if (conn != null)' check, in the finally block, will
> be false and the connection won't be closed a second time. The only time
> the connection will be closed in the finally block is if some Exception
> gets thrown before the call to conn.close() in the try block, in which 
> case
> the first conn.close() will not have been called. In short, if you copied
> this code, your connections shouldn't be getting closed twice. That being
> said, I'm not sure what the utility of closing the Connection in two 
> places
> really is; why not just do it in the finally block?
>
<removed examples>



Mime
View raw message