/*
* file: FinallyForClosure.java
* package: oreilly.hcj.exceptions
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
########## DO NOT EDIT ABOVE THIS LINE ########## */
package oreilly.hcj.exceptions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Demonstrates using finally for closure.
*
* @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
* @version $Revision: 1.3 $
*/
public class FinallyForClosure {
/**
* Gets a value from the database.
*
* @param conn The database connection to use.
* @param sql The SQL to use.
*
* @return The result value.
*
* @throws SQLException If there is a SQL error.
*/
public int getValue(final Connection conn, final String sql)
throws SQLException {
int result = 0;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
result = rs.getInt(1);
}
} catch (final SQLException ex) {
throw ex;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
return result;
}
/**
* Gets a value from the database.
*
* @param conn The database connection to use.
* @param sql The SQL to use.
*
* @return The result value.
*
* @throws SQLException If there is a SQL error.
*/
public int getValue2(final Connection conn, final String sql)
throws SQLException {
int result = 0;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
result = rs.getInt(1);
}
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
return result;
}
}
/* ########## End of File ########## */
|