Example usage for java.sql ResultSetMetaData getColumnLabel

List of usage examples for java.sql ResultSetMetaData getColumnLabel

Introduction

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

Prototype

String getColumnLabel(int column) throws SQLException;

Source Link

Document

Gets the designated column's suggested title for use in printouts and displays.

Usage

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//from w  w w  . ja va  2s.c o m
        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;
}

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();
    }//w w  w. j  a v a2s .  c o m

    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:com.tesora.dve.client.ClientTestNG.java

@Test
public void infoSchemaColumnMetadataTest() throws Exception {
    StringBuffer query = new StringBuffer().append("SHOW DATABASES");
    dbHelper.executeQuery(query.toString());

    ResultSet rs = dbHelper.getResultSet();
    ResultSetMetaData rsmd = rs.getMetaData();

    // make sure the column header is not empty
    assertTrue(!StringUtils.isEmpty(rsmd.getColumnLabel(1)));
    assertEquals(ShowSchema.Database.NAME, rsmd.getColumnLabel(1));
}

From source file:org.tradex.jdbc.JDBCHelper.java

/**
 * Executes the passed SQL and returns the resulting rows maps of values keyed by column name within a map keyed by rownumber (starting with zero)  
 * @param sql The SQL to execute// w  w  w . j  a  v  a  2  s  .c  o m
 * @return the results
 */
public Map<Integer, Map<String, Object>> result(CharSequence sql) {
    Map<Integer, Map<String, Object>> results = new TreeMap<Integer, Map<String, Object>>();
    Map<Integer, String> colNumToName;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rset = null;
    try {
        conn = ds.getConnection();
        ps = conn.prepareStatement(sql.toString());
        rset = ps.executeQuery();
        int colCount = rset.getMetaData().getColumnCount();
        colNumToName = new HashMap<Integer, String>(colCount);
        ResultSetMetaData rsmd = rset.getMetaData();
        for (int i = 1; i <= colCount; i++) {
            colNumToName.put(i, rsmd.getColumnLabel(i));
        }
        int rowNum = 0;
        while (rset.next()) {
            Map<String, Object> row = new HashMap<String, Object>(colCount);
            results.put(rowNum, row);
            for (int i = 1; i <= colCount; i++) {
                row.put(colNumToName.get(i), rset.getObject(i));
            }
            rowNum++;
        }
        return results;
    } catch (Exception e) {
        throw new RuntimeException("Query for [" + sql + "] failed", e);
    } finally {
        try {
            rset.close();
        } catch (Exception e) {
        }
        try {
            ps.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:chh.utils.db.source.common.JdbcClient.java

public List<List<Column>> select(String sqlQuery, List<Column> queryParams) {
    Connection connection = null;
    try {/*www  .j  a  v a 2 s  .c  om*/
        connection = connectionProvider.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
        if (queryTimeoutSecs > 0) {
            preparedStatement.setQueryTimeout(queryTimeoutSecs);
        }
        setPreparedStatementParams(preparedStatement, queryParams);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<List<Column>> rows = Lists.newArrayList();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<Column> row = Lists.newArrayList();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = metaData.getColumnLabel(i);
                int columnType = metaData.getColumnType(i);
                Class columnJavaType = Util.getJavaType(columnType);
                if (columnJavaType.equals(String.class)) {
                    row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType));
                } else if (columnJavaType.equals(Integer.class)) {
                    row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType));
                } else if (columnJavaType.equals(Double.class)) {
                    row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType));
                } else if (columnJavaType.equals(Float.class)) {
                    row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType));
                } else if (columnJavaType.equals(Short.class)) {
                    row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType));
                } else if (columnJavaType.equals(Boolean.class)) {
                    row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType));
                } else if (columnJavaType.equals(byte[].class)) {
                    row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType));
                } else if (columnJavaType.equals(Long.class)) {
                    row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType));
                } else if (columnJavaType.equals(Date.class)) {
                    row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType));
                } else if (columnJavaType.equals(Time.class)) {
                    row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType));
                } else if (columnJavaType.equals(Timestamp.class)) {
                    row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel),
                            columnType));
                } else {
                    throw new RuntimeException(
                            "type =  " + columnType + " for column " + columnLabel + " not supported.");
                }
            }
            rows.add(row);
        }
        return rows;
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute select query " + sqlQuery, e);
    } finally {
        closeConnection(connection);
    }
}

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

/**
 * Create a text array that contains the headings of the columns in the given result set.
 *
 * @param resultSet                  The result set that we want to create column headers for
 * @param preferColumnLabelForHeader True if we want to use the label (if available) for a column or use it's name if unavailable or false
 *
 * @return The headings/*from w w w .ja v a 2s. c o m*/
 */
public String[] getColumnHeadings(ResultSet resultSet, boolean preferColumnLabelForHeader) throws SQLException {
    ResultSetMetaData rsmd = resultSet.getMetaData();
    int columnsCount = rsmd.getColumnCount();

    String[] header = new String[columnsCount];
    if (preferColumnLabelForHeader) {
        for (int i = 1; i < columnsCount; i++) {
            String label = rsmd.getColumnLabel(i);
            if (label != null && label.length() > 0)
                header[i - 1] = label;
            else
                header[i - 1] = rsmd.getColumnName(i);
        }
    } else {
        for (int i = 1; i < columnsCount; i++)
            header[i - 1] = rsmd.getColumnName(i);
    }

    return header;
}

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

@Override
public DataHeader fetchAll2(File snapshotDirectory, Timestamp modifiedAfter, String objectName,
        final String keyName, final String updateTimeColumnName) {
    File objectFile = new File(snapshotDirectory, "data-" + objectName + ".dat");
    final GenericConsumer genericConsumer = new SequenceFileConsumer(objectFile);
    final DataHeader dataHeader = new DataHeader();

    String sql = "SELECT * FROM " + objectName + " o where o.update_time >= ?";

    getJdbcTemplate().query(sql, new Object[] { modifiedAfter }, new RowCallbackHandler() {

        @Override/*from   w ww .j a va2s  . c o  m*/
        public void processRow(ResultSet row) throws SQLException {
            final Map<String, Object> dataMap = new HashMap<String, Object>();
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                dataMap.put(rsm.getColumnName(column), row.getObject(rsm.getColumnLabel(column)));
            }

            DataRecord dataRecord = new GenericDataRecord(dataMap, keyName, globalMvdbKeyMaker,
                    updateTimeColumnName, new GlobalMvdbUpdateTimeMaker());
            genericConsumer.consume(dataRecord);
            dataHeader.incrementCount();

        }
    });

    genericConsumer.flushAndClose();

    writeDataHeader(dataHeader, objectName, snapshotDirectory);
    return dataHeader;
}

From source file:esg.gateway.service.ESGAccessLogServiceImpl.java

/**
   Initializes the service by setting up the database connection and result handling.
*///from w  w  w.ja va2  s  .co  m
public void init() {
    Properties props = new Properties();
    props.setProperty("db.protocol", "jdbc:postgresql:");
    props.setProperty("db.host", "localhost");
    props.setProperty("db.port", "5432");
    props.setProperty("db.database", "esgcet");
    props.setProperty("db.user", "dbsuper");
    props.setProperty("db.password", "changeme");
    try {
        props.putAll(new ESGFProperties());
    } catch (IOException ex) {
        log.error(ex);
    }

    queryRunner = new QueryRunner(DatabaseResource.init(props.getProperty("db.driver", "org.postgresql.Driver"))
            .setupDataSource(props).getDataSource());

    resultSetHandler = new ResultSetHandler<List<String[]>>() {
        public List<String[]> handle(ResultSet rs) throws SQLException {
            ArrayList<String[]> results = new ArrayList<String[]>();
            String[] record = null;
            assert (null != results);

            ResultSetMetaData meta = rs.getMetaData();
            int cols = meta.getColumnCount();
            log.trace("Number of fields: " + cols);

            log.trace("adding column data...");
            record = new String[cols];
            for (int i = 0; i < cols; i++) {
                try {
                    record[i] = meta.getColumnLabel(i + 1) + "|" + meta.getColumnType(i + 1);
                } catch (SQLException e) {
                    log.error(e);
                }
            }
            results.add(record);

            for (int i = 0; rs.next(); i++) {
                log.trace("Looking at record " + (i + 1));
                record = new String[cols];
                for (int j = 0; j < cols; j++) {
                    record[j] = rs.getString(j + 1);
                    log.trace("gathering result record column " + (j + 1) + " -> " + record[j]);
                }
                log.trace("adding record ");
                results.add(record);
                record = null; //gc courtesy
            }
            return results;
        }
    };
    log.trace("initialization complete");
}

From source file:com.cloudera.recordbreaker.analyzer.DataQuery.java

public List<List<Object>> query(DataDescriptor desc1, DataDescriptor desc2, String projectionClause,
        String selectionClause) throws SQLException, IOException {
    String tablename1 = grabTable(desc1);
    String tablename2 = null;//from   w ww .  j  a va  2 s . co  m
    if (desc2 != null) {
        tablename2 = grabTable(desc2);
    }

    //
    // Build the SQL query against the table
    //
    if (projectionClause == null || projectionClause.trim().length() == 0) {
        projectionClause = "*";
    }
    if (selectionClause == null) {
        selectionClause = "";
    }
    if (tablename2 == null) {
        projectionClause = projectionClause.replaceAll("DATA", tablename1);
        selectionClause = selectionClause.replaceAll("DATA", tablename1);
    }
    projectionClause = projectionClause.trim();
    selectionClause = selectionClause.trim();
    String query;
    if (tablename2 == null) {
        query = "SELECT " + projectionClause + " FROM " + tablename1;
    } else {
        query = "SELECT " + projectionClause + " FROM " + tablename1 + " DATA1" + ", " + tablename2 + " DATA2";
    }

    if (selectionClause.length() > 0) {
        query = query + " WHERE " + selectionClause;
    }

    //
    // Try to run it first with the impala connection.
    // If that fails, try hive.
    //
    List<List<Object>> result = new ArrayList<List<Object>>();
    Statement stmt = impalaCon.createStatement();
    LOG.info("Processing: " + query);
    try {
        ResultSet res = null;
        try {
            res = stmt.executeQuery(query);
            LOG.info("Ran Impala query: " + query);
        } catch (Exception iex) {
            iex.printStackTrace();
            // Fail back to Hive!
            stmt.close();
            stmt = hiveCon.createStatement();
            res = stmt.executeQuery(query);
            LOG.info("Ran Hive query: " + query);
        }

        // OK now do the real work
        ResultSetMetaData rsmd = res.getMetaData();
        List<Object> metatuple = new ArrayList<Object>();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            metatuple.add(rsmd.getColumnLabel(i));
        }
        result.add(metatuple);

        while (res.next()) {
            List<Object> tuple = new ArrayList<Object>();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                tuple.add(res.getObject(i));
            }
            result.add(tuple);
        }
        return result;
    } finally {
        stmt.close();
    }
}

From source file:com.slemarchand.sqlqueryscripting.scripting.sqlquery.SQLQueryExecutor.java

private List<List<Object>> _execQuery(String sqlQuery, int maxRows, List<String> columnLabels)
        throws SQLException {

    List<List<Object>> rows = null;

    Connection con = null;//from   w w w. ja  va  2  s .c om
    Statement stmt = null;
    ResultSet rs = null;

    try {
        con = DataAccess.getConnection();

        con.setAutoCommit(false); // Prevent data updates

        stmt = con.createStatement();
        stmt.setMaxRows(maxRows);
        rs = stmt.executeQuery(sqlQuery);

        ResultSetMetaData md = rs.getMetaData();
        int cc = md.getColumnCount();

        rows = new ArrayList<List<Object>>(cc);

        columnLabels.clear();

        for (int c = 1; c <= cc; c++) {
            String cl = md.getColumnLabel(c);
            columnLabels.add(cl);
        }

        while (rs.next()) {
            List<Object> row = new ArrayList<Object>(cc);
            for (int c = 1; c <= cc; c++) {
                Object value = rs.getObject(c);
                row.add(value);
            }
            rows.add(row);
        }

    } finally {
        DataAccess.cleanUp(con, stmt, rs);
    }

    return rows;
}