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.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java

public String writeTable(ResultSet results, ResultSetMetaData resultsMetaData)
        throws IOException, SQLException {
    int numColumns = resultsMetaData.getColumnCount();
    results.beforeFirst();//ww w.  j ava  2s.  c  om
    StringBuffer t = new StringBuffer();
    t.append("<p>");

    if (results.next()) {
        for (int i = 1; i < (numColumns + 1); i++) {
            t.append(resultsMetaData.getColumnName(i));
            t.append(", ");
        }

        t.append("<br />");
        results.beforeFirst();

        while (results.next()) {

            for (int i = 1; i < (numColumns + 1); i++) {
                t.append(results.getString(i));
                t.append(", ");
            }

            t.append("<br />");
        }

    } else {
        t.append("Query Successful; however no data was returned from this query.");
    }

    t.append("</p>");
    return (t.toString());
}

From source file:org.apache.tika.parser.jdbc.JDBCTableReader.java

private void handleCell(ResultSetMetaData rsmd, int i, ContentHandler handler, ParseContext context)
        throws SQLException, IOException, SAXException {
    switch (rsmd.getColumnType(i)) {
    case Types.BLOB:
        handleBlob(tableName, rsmd.getColumnName(i), rows, results, i, handler, context);
        break;/*from  w  w w. j av  a  2  s. c  o m*/
    case Types.CLOB:
        handleClob(tableName, rsmd.getColumnName(i), rows, results, i, handler, context);
        break;
    case Types.BOOLEAN:
        handleBoolean(results, i, handler);
        break;
    case Types.DATE:
        handleDate(results, i, handler);
        break;
    case Types.TIMESTAMP:
        handleTimeStamp(results, i, handler);
        break;
    case Types.INTEGER:
        handleInteger(results, i, handler);
        break;
    case Types.FLOAT:
        //this is necessary to handle rounding issues in presentation
        //Should we just use getString(i)?
        float f = results.getFloat(i);
        if (!results.wasNull()) {
            addAllCharacters(Float.toString(f), handler);
        }
        break;
    case Types.DOUBLE:
        double d = results.getDouble(i);
        if (!results.wasNull()) {
            addAllCharacters(Double.toString(d), handler);
        }
        break;
    default:
        String s = results.getString(i);
        if (!results.wasNull()) {
            addAllCharacters(s, handler);
        }
        break;
    }
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

private TableModel retrieveDatasetForQuery(String directory, String query, ObjectId head)
        throws CitationDBException {

    try (Connection conn = getCSVConnection(directory)) {
        Statement stmt = conn.createStatement();
        ResultSet set = stmt.executeQuery(query);
        ResultSetMetaData metaData = set.getMetaData();
        int columnCount = metaData.getColumnCount();

        String[] columns = new String[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columns[i - 1] = metaData.getColumnName(i);
        }/*from   w ww.j  a va2  s  . c  o  m*/

        TableModelMetaData tableMetaData = new DefaultTableModelMetaData(new DefaultRevision(head.getName()));
        DefaultTableModel model = new DefaultTableModel(tableMetaData, Arrays.asList(columns));

        while (set.next()) {
            String[] row = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                row[i - 1] = (String) set.getObject(i);

            }
            model.addRow(row);
        }

        return model;
    } catch (SQLException e) {
        throw new CitationDBException(e);
    }
}

From source file:com.netspective.axiom.sql.ResultSetUtils.java

public Map[] getResultSetRowsAsMapArray(ResultSet rs, boolean useLabelAsKey) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colsCount = rsmd.getColumnCount();
    String[] columnNames = new String[colsCount];
    for (int c = 1; c <= colsCount; c++) {
        columnNames[c - 1] = useLabelAsKey ? rsmd.getColumnLabel(c).toLowerCase()
                : rsmd.getColumnName(c).toLowerCase();
    }//from w  w w .jav  a2  s . c om

    ArrayList result = new ArrayList();
    while (rs.next()) {
        Map rsMap = new HashMap();
        for (int i = 1; i <= colsCount; i++) {
            rsMap.put(columnNames[i - 1], rs.getObject(i));
        }
        result.add(rsMap);
    }

    if (result.size() > 0)
        return (Map[]) result.toArray(new Map[result.size()]);
    else
        return null;
}

From source file:org.apache.ddlutils.platform.ModelBasedResultSetIterator.java

/**
 * Initializes this iterator from the resultset metadata.
 * /*from w ww .  j a v a 2 s.  c om*/
 * @param model The database model
 */
private void initFromMetaData(Database model) throws SQLException {
    ResultSetMetaData metaData = _resultSet.getMetaData();
    String tableName = null;
    boolean singleKnownTable = true;

    for (int idx = 1; idx <= metaData.getColumnCount(); idx++) {
        String columnName = metaData.getColumnName(idx);
        String tableOfColumn = metaData.getTableName(idx);
        Table table = null;

        if ((tableOfColumn != null) && (tableOfColumn.length() > 0)) {
            // jConnect might return a table name enclosed in quotes
            if (tableOfColumn.startsWith("\"") && tableOfColumn.endsWith("\"")
                    && (tableOfColumn.length() > 1)) {
                tableOfColumn = tableOfColumn.substring(1, tableOfColumn.length() - 1);
            }
            // the JDBC driver gave us enough meta data info
            table = model.findTable(tableOfColumn, _caseSensitive);
        }
        if (table == null) {
            // not enough info in the meta data of the result set, lets try the
            // user-supplied query hints
            table = (Table) _preparedQueryHints.get(_caseSensitive ? columnName : columnName.toLowerCase());
            tableOfColumn = (table == null ? null : table.getName());
        }
        if (tableName == null) {
            tableName = tableOfColumn;
        } else if (!tableName.equals(tableOfColumn)) {
            singleKnownTable = false;
        }

        String propName = columnName;

        if (table != null) {
            Column column = table.findColumn(columnName, _caseSensitive);

            if (column != null) {
                propName = column.getName();
            }
        }
        _columnsToProperties.put(columnName, propName);
    }
    if (singleKnownTable && (tableName != null)) {
        _dynaClass = model.getDynaClassFor(tableName);
    } else {
        DynaProperty[] props = new DynaProperty[_columnsToProperties.size()];
        int idx = 0;

        for (Iterator it = _columnsToProperties.values().iterator(); it.hasNext(); idx++) {
            props[idx] = new DynaProperty((String) it.next());
        }
        _dynaClass = new BasicDynaClass("result", BasicDynaBean.class, props);
    }
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jdbc.JDBCGatherer.java

/**
 * Gathers attributes from JDBC storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//*from ww  w  .  jav a2s  . c  om*/
@Override
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    PreparedStatement oPreparedStatement = null;
    ResultSet oResultSet = null;
    Connection oConnection = null;
    try {
        oConnection = _oDataSource.getConnection();
        oPreparedStatement = oConnection.prepareStatement(_sSelectQuery);
        oPreparedStatement.setString(1, sUserId);
        oResultSet = oPreparedStatement.executeQuery();
        if (oResultSet.next()) {
            ResultSetMetaData oResultSetMetaData = oResultSet.getMetaData();
            int iCount = oResultSetMetaData.getColumnCount();
            for (int i = 1; i <= iCount; i++) {
                String sName = oResultSetMetaData.getColumnName(i);
                Object oValue = oResultSet.getObject(sName);

                String sMappedName = _htMapper.get(sName);
                if (sMappedName != null)
                    sName = sMappedName;

                if (oValue == null)
                    oValue = "";

                oAttributes.put(sName, oValue);
            }
        }
    } catch (SQLException e) {
        _logger.error("Could not gather attributes for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (Exception e) {
        _logger.fatal("Could not initialize object", e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oResultSet != null)
                oResultSet.close();
        } catch (Exception e) {
            _logger.error("Could not close resultset", e);
        }

        try {
            if (oPreparedStatement != null)
                oPreparedStatement.close();
        } catch (Exception e) {
            _logger.error("Could not close statement", e);
        }

        try {
            if (oConnection != null)
                oConnection.close();
        } catch (Exception e) {
            _logger.error("Could not disconnect prepared statement", e);
        }
    }
}

From source file:com.kumarvv.setl.core.Loader.java

/**
 * build select columns from database//  w w w .j a  v  a2s  . c o  m
 *
 * @param load
 * @return
 */
protected String buildSelectColumns(Load load) {
    if (load == null || StringUtils.isEmpty(load.getTable())) {
        return "";
    }

    StringBuilder sql = new StringBuilder();
    sql.append("SELECT * FROM ").append(load.getTable()).append(" WHERE 1>2");

    final Set<String> cols = new LinkedHashSet<>();
    try (JdbcRowSet cjrs = rowSetUtil.getRowSet(def.getToDS())) {
        cjrs.setCommand(sql.toString());
        cjrs.execute();
        ResultSetMetaData meta = cjrs.getMetaData();
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            cols.add(meta.getColumnName(i).toLowerCase());
        }
    } catch (SQLException sqle) {
        Logger.error("buildSelectColumns failed: " + sqle.getMessage());
        Logger.trace(sqle);
    }
    String colStr = StringUtils.join(cols, ", ");
    Logger.debug("load={}, selectColumns={}", load.getTable(), sql.toString());
    return colStr;
}

From source file:com.modelmetrics.cloudconverter.forceutil.DataUpsertExecutor.java

public void executeWithResultSet(MigrationContext migrationContext) throws Exception {

    log.debug("starting data transfer (upsert)...");

    dao.setSalesforceSession(migrationContext.getSalesforceSession());

    Collection<Sproxy> toUpsert = new ArrayList<Sproxy>();

    ResultSet rs = migrationContext.getResultSet();
    ResultSetMetaData rsmd = migrationContext.getResultSetMetaData();

    if (rs == null) {
        log.info("result set is null");
    }//from w  w  w  .j  a  va2 s.c  om

    while (rs.next()) {

        Sproxy current = sproxyBuilder.buildEmpty(migrationContext.getCustomObject().getFullName());

        for (int i = 0; i < rsmd.getColumnCount(); i++) {
            current.setValue(migrationContext.getFieldMap().get(rsmd.getColumnName(i + 1)),
                    rs.getObject(i + 1));
        }

        toUpsert.add(current);

        if (toUpsert.size() == MAX_SPROXY_BATCH_SIZE) {
            dao.upsert(migrationContext.getExternalIdForUpsert(), toUpsert);
            toUpsert = new ArrayList<Sproxy>();
        }

    }

    log.debug("starting the upsert..." + migrationContext.getExternalIdForUpsert());

    dao.upsert(migrationContext.getExternalIdForUpsert(), toUpsert);

    log.debug("insert complete...");

}

From source file:org.apache.tajo.cli.tsql.DefaultTajoCliOutputFormatter.java

@Override
public void printResult(PrintWriter sout, InputStream sin, TableDesc tableDesc, float responseTime,
        ResultSet res) throws Exception {
    long resultRows = tableDesc.getStats() == null ? -1 : tableDesc.getStats().getNumRows();
    if (resultRows == -1) {
        resultRows = Integer.MAX_VALUE;
    }//from  ww  w.  j  a v a 2  s.co  m

    if (res == null) {
        sout.println(getQuerySuccessMessage(tableDesc, responseTime, 0, "inserted", true));
        return;
    }
    ResultSetMetaData rsmd = res.getMetaData();
    int numOfColumns = rsmd.getColumnCount();
    for (int i = 1; i <= numOfColumns; i++) {
        if (i > 1)
            sout.print(",  ");
        String columnName = rsmd.getColumnName(i);
        sout.print(columnName);
    }
    sout.println("\n-------------------------------");

    int numOfPrintedRows = 0;
    int totalPrintedRows = 0;
    boolean endOfTuple = true;
    while (res.next()) {
        for (int i = 1; i <= numOfColumns; i++) {
            if (i > 1)
                sout.print(",  ");
            String columnValue = res.getString(i);
            if (res.wasNull()) {
                sout.print(nullChar);
            } else {
                sout.print(columnValue);
            }
        }
        sout.println();
        sout.flush();
        numOfPrintedRows++;
        totalPrintedRows++;
        if (printPause && printPauseRecords > 0 && totalPrintedRows < resultRows
                && numOfPrintedRows >= printPauseRecords) {
            if (resultRows < Integer.MAX_VALUE) {
                sout.print("(" + totalPrintedRows + "/" + resultRows + " rows, continue... 'q' is quit)");
            } else {
                sout.print("(" + totalPrintedRows + " rows, continue... 'q' is quit)");
            }
            sout.flush();
            if (sin != null) {
                if (sin.read() == QUIT_COMMAND) {
                    endOfTuple = false;
                    sout.println();
                    break;
                }
            }
            numOfPrintedRows = 0;
            sout.println();
        }
    }
    sout.println(getQuerySuccessMessage(tableDesc, responseTime, totalPrintedRows, "selected", endOfTuple));
    sout.flush();
}

From source file:com.mvdb.etl.dao.impl.JdbcOrderDAO.java

@Override
public Map<String, ColumnMetadata> findMetadata() {
    String sql = "SELECT * FROM ORDERS limit 1";
    final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>();

    getJdbcTemplate().query(sql, new RowCallbackHandler() {

        @Override/* w w  w .  ja va  2  s.c  om*/
        public void processRow(ResultSet row) throws SQLException {
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                ColumnMetadata metadata = new ColumnMetadata();
                metadata.setColumnLabel(rsm.getColumnLabel(column));
                metadata.setColumnName(rsm.getColumnName(column));
                metadata.setColumnType(rsm.getColumnType(column));
                metadata.setColumnTypeName(rsm.getColumnTypeName(column));

                metaDataMap.put(rsm.getColumnName(column), metadata);
            }

        }
    });

    return metaDataMap;
}