in jelly-tags/sql/src/main/java/org/apache/commons/jelly/tags/sql/QueryTag.java [100:222]
public void doTag(XMLOutput output) throws JellyTagException {
if (!maxRowsSpecified) {
Object obj = context.getVariable("org.apache.commons.jelly.sql.maxRows");
if (obj != null) {
if (obj instanceof Integer) {
maxRows = ((Integer) obj).intValue();
}
else if (obj instanceof String) {
try {
maxRows = Integer.parseInt((String) obj);
}
catch (NumberFormatException nfe) {
throw new JellyTagException(
Resources.getMessage("SQL_MAXROWS_PARSE_ERROR", (String) obj),
nfe);
}
}
else {
throw new JellyTagException(Resources.getMessage("SQL_MAXROWS_INVALID"));
}
}
}
Result result = null;
String sqlStatement = null;
log.debug( "About to lookup connection" );
ResultSet rs = null;
Statement statement = null;
try {
conn = getConnection();
/*
* Use the SQL statement specified by the sql attribute, if any,
* otherwise use the body as the statement.
*/
if (sql != null) {
sqlStatement = sql;
}
else {
sqlStatement = getBodyText();
}
if (sqlStatement == null || sqlStatement.trim().length() == 0) {
throw new JellyTagException(Resources.getMessage("SQL_NO_STATEMENT"));
}
/*
* We shouldn't have a negative startRow or illegal maxrows
*/
if ((startRow < 0) || (maxRows < -1)) {
throw new JellyTagException(Resources.getMessage("PARAM_BAD_VALUE"));
}
/*
* Note! We must not use the setMaxRows() method on the
* the statement to limit the number of rows, since the
* Result factory must be able to figure out the correct
* value for isLimitedByMaxRows(); there's no way to check
* if it was from the ResultSet.
*/
if ( log.isDebugEnabled() ) {
log.debug( "About to execute query: " + sqlStatement );
}
if ( hasParameters() ) {
PreparedStatement ps = conn.prepareStatement(sqlStatement);
statement = ps;
setParameters(ps);
rs = ps.executeQuery();
}
else {
statement = conn.createStatement();
rs = statement.executeQuery(sqlStatement);
}
result = new ResultImpl(rs, startRow, maxRows);
context.setVariable(var, result);
// always close the result set first since it may be closed by
// JDBC 3 when closing statements
// lets nullify before we close in case we get exceptions
// while closing, we don't want to try to close again
ResultSet tempRs = rs;
rs = null;
tempRs.close();
Statement tempStatement = statement;
statement = null;
tempStatement.close();
}
catch (SQLException e) {
throw new JellyTagException(sqlStatement + ": " + e.getMessage(), e);
}
finally {
if (rs != null) {
try {
rs.close();
}
catch (SQLException e) {
log.error("Caught exception while closing result set: " + e, e);
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
log.error("Caught exception while closing statement: " + e, e);
}
}
if (conn != null && !isPartOfTransaction) {
try {
conn.close();
}
catch (SQLException e) {
log.error("Caught exception while closing connection: " + e, e);
}
conn = null;
}
clearParameters();
}
}