Example usage for java.sql ResultSetMetaData getColumnName

List of usage examples for java.sql ResultSetMetaData getColumnName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnName.

Prototype

String getColumnName(int column) throws SQLException;

Source Link

Document

Get the designated column's name.

Usage

From source file:org.apache.zeppelin.hopshive.HopsHiveInterpreter.java

private String getResults(ResultSet resultSet, boolean isTableType) throws SQLException {
    ResultSetMetaData md = resultSet.getMetaData();
    StringBuilder msg;/*ww  w.jav  a  2  s .c om*/
    if (isTableType) {
        msg = new StringBuilder(TABLE_MAGIC_TAG);
    } else {
        msg = new StringBuilder();
    }

    for (int i = 1; i < md.getColumnCount() + 1; i++) {
        if (i > 1) {
            msg.append(TAB);
        }
        msg.append(replaceReservedChars(md.getColumnName(i)));
    }
    msg.append(NEWLINE);

    int displayRowCount = 0;
    while (displayRowCount < getMaxResult() && resultSet.next()) {
        for (int i = 1; i < md.getColumnCount() + 1; i++) {
            Object resultObject;
            String resultValue;
            resultObject = resultSet.getObject(i);
            if (resultObject == null) {
                resultValue = "null";
            } else {
                resultValue = resultSet.getString(i);
            }
            msg.append(replaceReservedChars(resultValue));
            if (i != md.getColumnCount()) {
                msg.append(TAB);
            }
        }
        msg.append(NEWLINE);
        displayRowCount++;
    }
    return msg.toString();
}

From source file:org.codehaus.mojo.dbupgrade.sqlexec.DefaultSQLExec.java

/**
 * print any results in the result set./*from  ww  w .  jav  a 2  s . c o m*/
 *
 * @param rs the resultset to print information about
 * @param out the place to print results
 * @throws SQLException on SQL problems.
 */
private void printResultSet(ResultSet rs, PrintStream out) throws SQLException {
    if (rs != null) {
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        StringBuffer line = new StringBuffer();
        if (config.isShowheaders()) {
            for (int col = 1; col < columnCount; col++) {
                line.append(md.getColumnName(col));
                line.append(",");
            }
            line.append(md.getColumnName(columnCount));
            out.println(line);
            line = new StringBuffer();
        }
        while (rs.next()) {
            boolean first = true;
            for (int col = 1; col <= columnCount; col++) {
                String columnValue = rs.getString(col);
                if (columnValue != null) {
                    columnValue = columnValue.trim();
                }

                if (first) {
                    first = false;
                } else {
                    line.append(",");
                }
                line.append(columnValue);
            }
            out.println(line);
            line = new StringBuffer();
        }
    }
    out.println();
}

From source file:net.ymate.platform.persistence.jdbc.scaffold.EntityGenerator.java

/**
 * @param dbName     ???//from  w ww .  j  a v a  2s  .co  m
 * @param dbUserName ??
 * @param tableName  ??
 * @return ?????
 */
private TableMeta getTableMeta(String dbName, String dbUserName, String tableName) {
    IConnectionHolder _connHolder = null;
    Statement _statement = null;
    ResultSet _resultSet = null;
    Map<String, ColumnInfo> _tableFields = new LinkedHashMap<String, ColumnInfo>();
    List<String> _pkFields = new LinkedList<String>();
    TableMeta _meta = new TableMeta(_pkFields, _tableFields);
    try {
        _connHolder = __jdbc.getDefaultConnectionHolder();
        String _dbType = _connHolder.getDialect().getName();
        DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData();
        System.out.println(">>> Catalog: " + dbName);
        System.out.println(">>> Schema: " + dbUserName);
        System.out.println(">>> Table: " + tableName);
        _resultSet = _dbMetaData.getPrimaryKeys(dbName,
                _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName);
        if (_resultSet == null) {
            System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored");
            return null;
        } else {
            while (_resultSet.next()) {
                _pkFields.add(_resultSet.getString(4).toLowerCase());
            }
            if (_pkFields.isEmpty()) {
                System.err
                        .println("Database table \"" + tableName + "\" does not set the primary key, ignored");
                return null;
            } else {
                //
                System.out.println(">>> " + "COLUMN_NAME / " + "COLUMN_CLASS_NAME / " + "PRIMARY_KEY / "
                        + "AUTO_INCREMENT / " + "SIGNED / " + "PRECISION / " + "SCALE / " + "NULLABLE / "
                        + "DEFAULT / " + "REMARKS");
                //
                _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                _resultSet = _statement.executeQuery(
                        "SELECT * FROM ".concat(_connHolder.getDialect().wrapIdentifierQuote(tableName)));
                ResultSetMetaData _rsMetaData = _resultSet.getMetaData();
                //
                for (int _idx = 1; _idx <= _rsMetaData.getColumnCount(); _idx++) {
                    // ??
                    ResultSet _column = _dbMetaData.getColumns(dbName,
                            _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName,
                            tableName, _rsMetaData.getColumnName(_idx));
                    if (_column.next()) {
                        // ????
                        _tableFields.put(_rsMetaData.getColumnName(_idx).toLowerCase(),
                                new ColumnInfo(_rsMetaData.getColumnName(_idx).toLowerCase(),
                                        _rsMetaData.getColumnClassName(_idx), _rsMetaData.isAutoIncrement(_idx),
                                        _rsMetaData.isSigned(_idx), _rsMetaData.getPrecision(_idx),
                                        _rsMetaData.getScale(_idx), _rsMetaData.isNullable(_idx),
                                        _column.getString("COLUMN_DEF"), _column.getString("REMARKS")));
                        System.out.println("--> " + _rsMetaData.getColumnName(_idx).toLowerCase() + "\t"
                                + _rsMetaData.getColumnClassName(_idx) + "\t"
                                + _pkFields.contains(_rsMetaData.getColumnName(_idx).toLowerCase()) + "\t"
                                + _rsMetaData.isAutoIncrement(_idx) + "\t" + _rsMetaData.isSigned(_idx) + "\t"
                                + _rsMetaData.getPrecision(_idx) + "\t" + _rsMetaData.getScale(_idx) + "\t"
                                + _rsMetaData.isNullable(_idx) + "\t" + _column.getString("COLUMN_DEF") + "\t"
                                + _column.getString("REMARKS"));
                    }
                    _column.close();
                }
            }
        }
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    } finally {
        if (_statement != null) {
            try {
                _statement.close();
            } catch (SQLException e) {
                _LOG.warn("", e);
            }
        }
        if (_resultSet != null) {
            try {
                _resultSet.close();
            } catch (SQLException e) {
                _LOG.warn("", e);
            }
        }
        if (_connHolder != null) {
            _connHolder.release();
        }
    }
    return _meta;
}

From source file:net.ymate.platform.persistence.jdbc.scaffold.JdbcScaffold.java

/**
 * @param dbName ???// ww w . j a v a2s .  c o  m
 * @param dbUserName ??
 * @param tableName ??
 * @return ?????
 */
private TableMeta getTableMeta(String dbName, String dbUserName, String tableName) {
    IConnectionHolder _connHolder = null;
    Statement _statement = null;
    ResultSet _resultSet = null;
    Map<String, ColumnInfo> _tableFields = new LinkedHashMap<String, ColumnInfo>();
    List<String> _pkFields = new LinkedList<String>();
    TableMeta _meta = new TableMeta(_pkFields, _tableFields);
    try {
        _connHolder = JDBC.getConnectionHolder();
        String _dbType = JDBC_SCAFFOLD_CONF.getProperty("ymp.scaffold.jbdc.db_type", "unknow");
        DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData();
        _resultSet = _dbMetaData.getPrimaryKeys(dbName,
                _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName);
        if (_resultSet == null) {
            _meta = null;
            System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored");
        } else {
            while (_resultSet.next()) {
                _pkFields.add(_resultSet.getString(4).toLowerCase());
            }
            if (_pkFields.isEmpty()) {
                _meta = null;
                System.err
                        .println("Database table \"" + tableName + "\" does not set the primary key, ignored");
            } else {
                _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                _resultSet = _statement
                        .executeQuery("select * from " + _connHolder.getDialect().wapperQuotedIdent(tableName));
                ResultSetMetaData _rsMetaData = _resultSet.getMetaData();
                //
                for (int _idx = 1; _idx <= _rsMetaData.getColumnCount(); _idx++) {
                    // ??
                    ResultSet _column = _dbMetaData.getColumns(dbName,
                            _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName,
                            tableName, _rsMetaData.getColumnName(_idx));
                    if (_column.next()) {
                        // ????
                        _tableFields.put(_rsMetaData.getColumnName(_idx).toLowerCase(),
                                new ColumnInfo(_rsMetaData.getColumnName(_idx).toLowerCase(),
                                        compressType(_rsMetaData.getColumnClassName(_idx)),
                                        _rsMetaData.isAutoIncrement(_idx), _rsMetaData.isNullable(_idx),
                                        _column.getString("COLUMN_DEF")));
                    }
                }
                //
                System.err.println("TABLE_NAME: " + tableName + " ---------------->>");
                System.err.println("COLUMN_NAME\tPK\tCOLUMN_TYPE\tIS_AUTOINCREMENT\tIS_NULLABLE\tCOLUMN_DEF");
                for (ColumnInfo _cInfo : _tableFields.values()) {
                    System.err
                            .println(_cInfo.getColumnName() + "\t" + _pkFields.contains(_cInfo.getColumnName())
                                    + "\t" + _cInfo.getColumnType() + "\t" + _cInfo.isAutoIncrement() + "\t"
                                    + _cInfo.getNullable() + "\t" + _cInfo.getDefaultValue());
                }
            }
        }
    } catch (Throwable e) {
        if (e instanceof Error) {
            throw (Error) e;
        }
        throw new Error(RuntimeUtils.unwrapThrow(e));
    } finally {
        _connHolder.release();
        _statement = null;
        _resultSet = null;
    }
    return _meta;
}

From source file:org.acmsl.queryj.metadata.engines.MetadataManagerTableDAO.java

/**
 * Queries the contents of given table.// w  w w .  j a v a  2  s  .c  om
 * @param tableName the table name.
 * @param staticAttributeName the static attribute name.
 * @param attributes the attributes.
 * @param connection the connection.
 * @return the retrieved rows.
 * @throws SQLException if the contents cannot be retrieved.
 */
@NotNull
protected List<Row<String>> queryContents(@NotNull final String tableName,
        @Nullable final String staticAttributeName, @NotNull final List<Attribute<String>> attributes,
        @NotNull final Connection connection) throws SQLException {
    // TODO: Move this to TableDAO
    @NotNull
    final List<Row<String>> result = new ArrayList<>();

    @Nullable
    final Log t_Log = UniqueLogFactory.getLog(DAOTemplateUtils.class);

    final int t_iColumnCount = attributes.size();

    @Nullable
    ResultSet t_rsResults = null;

    @Nullable
    PreparedStatement t_PreparedStatement = null;

    try {
        t_PreparedStatement = connection.prepareStatement("select * from " + tableName);

        t_rsResults = t_PreparedStatement.executeQuery();

        @NotNull
        final String[] t_astrColumnNames = new String[t_iColumnCount];

        @NotNull
        final String[] t_astrColumnValues = new String[t_iColumnCount];

        @Nullable
        String t_strRowName;

        if (t_rsResults != null) {
            while (t_rsResults.next()) {
                t_strRowName = null;

                @NotNull
                final ResultSetMetaData t_rsMetaData = t_rsResults.getMetaData();

                int t_iArrayIndex;

                for (int t_iIndex = 1; t_iIndex <= t_iColumnCount; t_iIndex++) {
                    t_iArrayIndex = t_iIndex - 1;

                    t_astrColumnNames[t_iArrayIndex] = t_rsMetaData.getColumnName(t_iIndex);

                    t_astrColumnValues[t_iArrayIndex] = t_rsResults.getString(t_iIndex);

                    if (staticAttributeName.equalsIgnoreCase(t_astrColumnNames[t_iArrayIndex])) {
                        t_strRowName = t_astrColumnValues[t_iArrayIndex];
                    }
                }

                reorderAttributes(attributes, t_astrColumnNames, t_astrColumnValues);

                @NotNull
                final List<Attribute<String>> t_lAttributes = new ArrayList<>(t_astrColumnValues.length);

                Attribute<String> t_NewAttribute;

                for (int t_iIndex = 0; t_iIndex < t_astrColumnValues.length; t_iIndex++) {
                    @Nullable
                    final Attribute<String> t_Attribute = attributes.get(t_iIndex);

                    if (t_Attribute != null) {
                        t_NewAttribute = new AttributeValueObject(t_Attribute.getName(),
                                t_Attribute.getTypeId(), t_Attribute.getType(), t_Attribute.getTableName(),
                                t_Attribute.getComment(), t_Attribute.getOrdinalPosition(),
                                t_Attribute.getLength(), t_Attribute.getPrecision(), t_Attribute.getKeyword(),
                                t_Attribute.getRetrievalQuery(), t_Attribute.getSequence(),
                                t_Attribute.isNullable(), t_astrColumnValues[t_iIndex],
                                t_Attribute.isReadOnly(), t_Attribute.isBoolean(), t_Attribute.getBooleanTrue(),
                                t_Attribute.getBooleanFalse(), t_Attribute.getBooleanNull());

                        t_lAttributes.add(t_NewAttribute);
                    }
                }

                result.add(buildRow(t_strRowName, tableName, t_lAttributes));
            }
        }
    } finally {
        try {
            if (t_rsResults != null) {
                t_rsResults.close();
            }
        } catch (@NotNull final SQLException sqlException) {
            if (t_Log != null) {
                t_Log.error("Cannot close the ResultSet.", sqlException);
            }
        }

        try {
            if (t_PreparedStatement != null) {
                t_PreparedStatement.close();
            }
        } catch (@NotNull final SQLException sqlException) {
            if (t_Log != null) {
                t_Log.error("Cannot close the PreparedStatement.", sqlException);
            }
        }
    }

    return result;
}

From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java

private JSONArray toJSONArray(ResultSet rs, JSONArray json) throws Exception {

    String temp = null;/*from   w  ww .  j  a v a 2 s. c  o m*/
    try {

        // we will need the column names, this will save the table meta-data like column nmae.
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        //loop through the ResultSet
        while (rs.next()) {

            //figure out how many columns there are
            int numColumns = rsmd.getColumnCount();

            //each row in the ResultSet will be converted to a JSON Object
            JSONObject obj = new JSONObject();

            // loop through all the columns and place them into the JSON Object
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);
                if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                    obj.put(column_name, rs.getArray(column_name).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                    obj.put(column_name, rs.getBigDecimal(column_name).toBigInteger().toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                    obj.put(column_name, ((Boolean) rs.getBoolean(column_name)).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                    obj.put(column_name, rs.getBlob(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                    obj.put(column_name, ((Double) rs.getDouble(column_name)).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                    obj.put(column_name, ((Float) rs.getFloat(column_name)).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                    obj.put(column_name, ((Integer) rs.getInt(column_name)).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                    obj.put(column_name, rs.getNString(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                    //                        temp = rs.getString(column_name); //saving column data to temp variable
                    //                        temp = ESAPI.encoder().canonicalize(temp); //decoding data to base state
                    //                        temp = ESAPI.encoder().encodeForHTML(temp); //encoding to be browser safe
                    //                        obj.put(column_name, temp); //putting data into JSON object
                    //                    
                    obj.put(column_name, rs.getNString(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                    obj.put(column_name, ((Integer) rs.getInt(column_name)).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                    obj.put(column_name, ((Integer) rs.getInt(column_name)).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                    obj.put(column_name, rs.getDate(column_name).toString());

                } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                    obj.put(column_name, TimeStampUtils.dateTimeToString(rs.getTime(column_name)));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    obj.put(column_name, TimeStampUtils.timeStampToString(rs.getTimestamp(column_name)));

                } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                    obj.put(column_name, rs.getBigDecimal(column_name).toString());

                } else {
                    obj.put(column_name, rs.getObject(column_name));

                }
            } //end foreach
            json.add(obj);
        } //end while
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json; //return JSON array
}

From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java

public List<String> toStringList(ResultSet rs) throws Exception {

    List<String> list = new ArrayList<String>();
    try {/*  www.  j ava2  s.c om*/

        // we will need the column names, this will save the table meta-data like column nmae.
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        //loop through the ResultSet
        while (rs.next()) {

            //figure out how many columns there are
            int numColumns = rsmd.getColumnCount();

            //each row in the ResultSet will be converted to a JSON Object
            StringBuilder builder = new StringBuilder();
            // loop through all the columns and place them into the JSON Object
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);

                if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                    builder.append(rs.getArray(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                    builder.append(rs.getBoolean(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                    builder.append(rs.getBlob(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                    builder.append(rs.getDouble(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                    builder.append(rs.getFloat(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                    builder.append(rs.getNString(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                    //                        temp = rs.getString(column_name); //saving column data to temp variable
                    //                        temp = ESAPI.encoder().canonicalize(temp); //decoding data to base state
                    //                        temp = ESAPI.encoder().encodeForHTML(temp); //encoding to be browser safe
                    //                        obj.put(column_name, temp); //putting data into JSON object
                    //                    
                    builder.append(rs.getNString(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                    builder.append(rs.getDate(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                    builder.append(rs.getTime(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    builder.append(rs.getTimestamp(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                    builder.append(rs.getBigDecimal(column_name));

                } else {
                    builder.append(rs.getObject(column_name));

                }
            } //end foreach
            list.add(builder.toString());
        } //end while
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list; //return String list

}

From source file:bs.global.util.ExcelFactory.java

public void generate(OutputStream outputStream) throws Exception {
    try {//from w ww. j a va2  s.com
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

        if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) {
            throw new IllegalStateException("Number of types is not identical to number of resultset columns. "
                    + "Number of types: " + formatTypes.length + ". Number of columns: "
                    + resultSetMetaData.getColumnCount());
        }

        int currentRow = 0;
        HSSFRow row = sheet.createRow(currentRow);
        int numCols = resultSetMetaData.getColumnCount();
        boolean isAutoDecideFormatTypes;

        if (isAutoDecideFormatTypes = (formatTypes == null)) {
            formatTypes = new FormatType[numCols];
        }
        for (int i = 0; i < numCols; i++) {
            String title = resultSetMetaData.getColumnName(i + 1);
            writeCell(row, i, title, FormatType.TEXT, boldFont);
            if (isAutoDecideFormatTypes) {
                Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1));
                formatTypes[i] = getFormatType(_class);
            }
        }
        currentRow++;
        // Write report rows
        while (resultSet.next()) {
            row = sheet.createRow(currentRow++);
            for (int i = 0; i < numCols; i++) {
                Object value = resultSet.getObject(i + 1);
                writeCell(row, i, value, formatTypes[i]);
            }
        }
        // Autosize columns
        for (int i = 0; i < numCols; i++) {
            sheet.autoSizeColumn((short) i);
        }
        workbook.write(outputStream);
    } finally {
        outputStream.close();
    }
}

From source file:org.apache.sqoop.manager.SqlManager.java

protected Map<String, String> getColumnTypeNamesForRawQuery(String stmt) {
    ResultSet results;//from w w  w.j a  v a2  s.c o m
    try {
        results = execute(stmt);
    } catch (SQLException sqlE) {
        LOG.error("Error executing statement: " + sqlE.toString(), sqlE);
        release();
        return null;
    }

    try {
        Map<String, String> colTypeNames = new HashMap<String, String>();

        int cols = results.getMetaData().getColumnCount();
        ResultSetMetaData metadata = results.getMetaData();
        for (int i = 1; i < cols + 1; i++) {
            String colTypeName = metadata.getColumnTypeName(i);

            String colName = metadata.getColumnName(i);
            if (colName == null || colName.equals("")) {
                colName = metadata.getColumnLabel(i);
            }

            colTypeNames.put(colName, colTypeName);
        }

        return colTypeNames;
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + sqlException.toString());
        return null;
    } finally {
        try {
            results.close();
            getConnection().commit();
        } catch (SQLException sqlE) {
            LOG.warn("SQLException closing ResultSet: " + sqlE.toString());
        }

        release();
    }
}

From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java

/**
 * Similar to the same method in original pubtest utility, but doesn't throw an exception if 0 rows are returned
 * and uses existing(established) JDBC connection corresponding to its published datasource name.
 * //w w w. j ava  2s .  c om
 */
public static String executeProcedure(RegressionItem item, HashMap<String, Connection> cisConnections,
        String outputFile, String delimiter, String printOutputType) throws CompositeException {
    // Set the command and action name
    String command = "executeProcedure";
    String actionName = "REGRESSION_TEST";

    int rows = 0;
    String result = null;
    Connection conn = null;
    CallableStatement stmt = null;
    ResultSet rs = null;
    start = System.currentTimeMillis();
    long firstRowLatency = 0L;

    // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
    if (CommonUtils.isExecOperation()) {
        try {
            conn = getJdbcConnection(item.database, cisConnections); // don't need to check for null here.

            String URL = null;
            String userName = null;
            if (conn.getMetaData() != null) {
                if (conn.getMetaData().getURL() != null)
                    URL = conn.getMetaData().getURL();
                if (conn.getMetaData().getUserName() != null)
                    userName = conn.getMetaData().getUserName();
            }
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delimiter, printOutputType).  item.database="
                            + item.database + "  cisConnections.URL=" + URL + "  cisConnections.userName="
                            + userName + "  outputFile=" + outputFile + "  delimiter=" + delimiter
                            + "  printOutputType=" + printOutputType,
                    "");
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "DEBUG: connection to DB successful", "");

            String query = item.input.replaceAll("\n", " ");
            // Convert a CALL statement into a SELECT * FROM statement

            // { CALL SCH1.LookupProduct( 3 ) } --> SCH1.LookupProduce( 3 )
            if (query.toUpperCase().contains("CALL")) {
                query = "SELECT * FROM " + RegressionManagerUtils.getProcedure(query);
                ;
            }

            // Prepare the query
            stmt = (CallableStatement) conn.prepareCall(query);

            // Register output parameter types
            for (int i = 0; i < item.outTypes.length; i++) {
                if (!"-".equals(item.outTypes[i])) {
                    int jdbcType = -1;
                    try {
                        jdbcType = Types.class.getField(item.outTypes[i]).getInt(null);
                    } catch (Exception e) {
                        RegressionManagerUtils.error(item.lineNum, item.outTypes[i],
                                "No such JDBC type in java.sql.Types");
                    }
                    stmt.registerOutParameter(i + 1, jdbcType);
                }
            }
            stmt.executeQuery();

            // Print scalars
            ParameterMetaData pmd = stmt.getParameterMetaData();
            int params = pmd.getParameterCount();
            boolean addSep = false;
            String content = "";
            for (int i = 0; i < params; i++) {
                if (addSep) {
                    content += delimiter;
                }
                if (stmt.getObject(i + 1) != null)
                    content += stmt.getObject(i + 1).toString();
                else
                    content += "";
                addSep = true;
            }
            if (outputFile != null)
                CommonUtils.appendContentToFile(outputFile, content);
            RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");

            // Get the result cursor and metadata cursor        
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columns = rsmd.getColumnCount();

            // Get the column metadata                      
            addSep = false;
            content = "";
            for (int i = 0; i < columns; i++) {
                if (addSep) {
                    content += delimiter;
                }
                if (rsmd.getColumnName(i + 1) != null)
                    content += rsmd.getColumnName(i + 1).toString();
                else
                    content += "";
                addSep = true;
            }
            if (outputFile != null)
                CommonUtils.appendContentToFile(outputFile, content);
            RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");

            // Print cursors
            boolean firstRow = true;
            while (rs != null) {
                // Read the values
                while (rs.next()) {
                    if (firstRow) {
                        firstRowLatency = System.currentTimeMillis() - start;
                        firstRow = false;
                    }
                    addSep = false;
                    content = "";
                    for (int i = 0; i < columns; i++) {
                        if (addSep) {
                            content += delimiter;
                        }
                        if (rs.getObject(i + 1) != null)
                            content += rs.getObject(i + 1).toString();
                        else
                            content += "";
                        addSep = true;
                    }
                    if (outputFile != null)
                        CommonUtils.appendContentToFile(outputFile, content);
                    RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");
                    rows++;
                }
                stmt.getMoreResults();
                rs = stmt.getResultSet();
            }
        } catch (SQLException e) {
            throw new CompositeException("executeProcedure(): " + e.getMessage());
        } catch (Exception e) {
            throw new CompositeException("executeProcedure(): " + e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                rs = null;
                stmt = null;
                throw new CompositeException(
                        "executeProcedure(): unable to close ResultSet or Statement" + e.getMessage());
            }
        }
        RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeProcedure()", "");
    } else {
        logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                + "] WAS NOT PERFORMED.\n");
    }

    // <rows>:<firstRowLatency>
    result = "" + rows + ":" + firstRowLatency;
    return result;
    /* Note: to process this result string on the client invocation side use the following pattern:
     * 
     *    String result = RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delim, printOutputType, "results");
       String results[] = result.split(":");
       if (results.length > 1) {
          rowCount = Integer.valueOf(results[0]);
             firstRowLatency.addAndGet(Long.parseLong(results[1]));                    
       }                  
     */
}