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:org.voltdb.HsqlBackend.java

public VoltTable runDML(String dml) {
    dml = dml.trim();//from www  .j  a v  a  2s.  c o  m
    String indicator = dml.substring(0, 1).toLowerCase();
    if (indicator.equals("s") || // "s" is for "select ..."
            indicator.equals("(")) { // "(" is for "(select ... UNION ...)" et. al.
        try {
            Statement stmt = dbconn.createStatement();
            sqlLog.l7dlog(Level.DEBUG, LogKeys.sql_Backend_ExecutingDML.name(), new Object[] { dml }, null);
            sqlLog.debug("Executing " + dml);
            ResultSet rs = stmt.executeQuery(dml);
            ResultSetMetaData rsmd = rs.getMetaData();

            // note the index values here carefully
            VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String colname = rsmd.getColumnLabel(i);
                String type = rsmd.getColumnTypeName(i);
                //LOG.fine("Column type: " + type);
                if (type.equals("VARCHAR"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.STRING);
                else if (type.equals("TINYINT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.TINYINT);
                else if (type.equals("SMALLINT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.SMALLINT);
                else if (type.equals("INTEGER"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.INTEGER);
                else if (type.equals("BIGINT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.BIGINT);
                else if (type.equals("DECIMAL"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.DECIMAL);
                else if (type.equals("FLOAT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.FLOAT);
                else if (type.equals("TIMESTAMP"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.TIMESTAMP);
                else if (type.equals("VARBINARY"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.VARBINARY);
                else if (type.equals("CHARACTER"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.STRING);
                else
                    throw new ExpectedProcedureException(
                            "Trying to create a column in Backend with a (currently) unsupported type: "
                                    + type);
            }
            VoltTable table = new VoltTable(columns);
            while (rs.next()) {
                Object[] row = new Object[table.getColumnCount()];
                for (int i = 0; i < table.getColumnCount(); i++) {
                    if (table.getColumnType(i) == VoltType.STRING)
                        row[i] = rs.getString(i + 1);
                    else if (table.getColumnType(i) == VoltType.TINYINT)
                        row[i] = rs.getByte(i + 1);
                    else if (table.getColumnType(i) == VoltType.SMALLINT)
                        row[i] = rs.getShort(i + 1);
                    else if (table.getColumnType(i) == VoltType.INTEGER)
                        row[i] = rs.getInt(i + 1);
                    else if (table.getColumnType(i) == VoltType.BIGINT)
                        row[i] = rs.getLong(i + 1);
                    else if (table.getColumnType(i) == VoltType.DECIMAL)
                        row[i] = rs.getBigDecimal(i + 1);
                    else if (table.getColumnType(i) == VoltType.FLOAT)
                        row[i] = rs.getDouble(i + 1);
                    else if (table.getColumnType(i) == VoltType.VARBINARY)
                        row[i] = rs.getBytes(i + 1);
                    else if (table.getColumnType(i) == VoltType.TIMESTAMP) {
                        Timestamp t = rs.getTimestamp(i + 1);
                        if (t == null) {
                            row[i] = null;
                        } else {
                            // convert from millisecond to microsecond granularity
                            row[i] = new org.voltdb.types.TimestampType(t.getTime() * 1000);
                        }
                    } else {
                        throw new ExpectedProcedureException(
                                "Trying to read a (currently) unsupported type from a JDBC resultset.");
                    }
                    if (rs.wasNull()) {
                        // JDBC returns 0/0.0 instead of null. Put null into the row.
                        row[i] = null;
                    }
                }

                table.addRow(row);
            }
            stmt.close();
            rs.close();
            return table;
        } catch (Exception e) {
            if (e instanceof ExpectedProcedureException) {
                throw (ExpectedProcedureException) e;
            }
            sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e);
            throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e);
        }
    } else {
        try {
            Statement stmt = dbconn.createStatement();
            sqlLog.debug("Executing: " + dml);
            long ucount = stmt.executeUpdate(dml);
            sqlLog.debug("  result: " + String.valueOf(ucount));
            VoltTable table = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT));
            table.addRow(ucount);
            return table;
        } catch (SQLException e) {
            // glorious hack to determine if the error is a constraint failure
            if (e.getMessage().contains("constraint")) {
                sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_ConvertingHSQLExtoCFEx.name(), e);
                final byte messageBytes[] = e.getMessage().getBytes();
                ByteBuffer b = ByteBuffer.allocate(25 + messageBytes.length);
                b.putInt(messageBytes.length);
                b.put(messageBytes);
                b.put(e.getSQLState().getBytes());
                b.putInt(0); // ConstraintFailure.type
                try {
                    FastSerializer.writeString("HSQL", b);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                b.putInt(0);//Table size is 0
                b.rewind();
                throw new ConstraintFailureException(b);
            } else {
                sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e);
                throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e);
            }

        } catch (Exception e) {
            // rethrow an expected exception
            sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e);
            throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e);
        }
    }
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected Integer searchColumnByLabel(String label) throws SQLException {
    Integer columnIndex = null;//from   w  w  w . j  a  v a 2 s . com
    ResultSetMetaData metadata = resultSet.getMetaData();
    for (int i = 1; i <= metadata.getColumnCount(); i++) {
        String columnLabel = metadata.getColumnLabel(i);
        if (columnLabel != null && label.equalsIgnoreCase(columnLabel)) {
            columnIndex = i;
            break;
        }
    }
    return columnIndex;
}

From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java

/**
 * The positions in the returned array represent column numbers.  The
 * values stored at each position represent the index in the
 * <code>PropertyDescriptor[]</code> for the bean property that matches
 * the column name.  If no bean property was found for a column, the
 * position is set to <code>PROPERTY_NOT_FOUND</code>.
 *
 * @param rsmd The <code>ResultSetMetaData</code> containing column
 * information.//ww  w  .j  a  v  a2  s  .com
 *
 * @param props The bean property descriptors.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return An int[] with column index to property index mappings.  The 0th
 * element is meaningless because JDBC column indexing starts at 1.
 */
protected int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException {

    int cols = rsmd.getColumnCount();
    int[] columnToProperty = new int[cols + 1];
    Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

    for (int col = 1; col <= cols; col++) {
        String columnName = rsmd.getColumnLabel(col);
        if (null == columnName || 0 == columnName.length()) {
            columnName = rsmd.getColumnName(col);
        }
        for (int i = 0; i < props.length; i++) {

            if (columnName.equalsIgnoreCase(StringHelper.toUnderscore(props[i].getName()))) {
                columnToProperty[col] = i;
                break;
            }
        }
    }

    return columnToProperty;
}

From source file:org.jesterj.ingest.scanners.JdbcScanner.java

private String[] getColumnNames(ResultSet rs) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    String[] names = new String[meta.getColumnCount()];

    for (int i = 0; i < names.length; i++) {
        // NB: we're getting the label here, to support the SQL's "select a AS b".
        // If label not available, we'll get the plain column name.
        names[i] = meta.getColumnLabel(i + 1);
    }//from  www  . j  a  v a2  s. com
    return names;
}

From source file:org.athrun.android.framework.agent.common.DBCommandRunner.java

private String execute(String command) throws Exception {
    String[] args = command.split("" + (char) 18);
    String _command = args[0];//  w  w  w. j a  v a2 s. c o  m
    PreparedStatement prepareStatement = connection.prepareStatement(_command);
    ResultSet rs = prepareStatement.executeQuery();// execute(),executeBatch(),executeUpdate()
    StringBuilder sb = new StringBuilder();

    java.sql.ResultSetMetaData rsmd = prepareStatement.getMetaData();
    //
    int columnCount = rsmd.getColumnCount();
    //
    List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
    Map<String, Object> data = null;
    String recordIndex = null;
    String attribute = null;

    if (args.length == 3) {
        recordIndex = args[1];
        attribute = args[2];
    }
    //

    while (rs.next()) {
        data = new HashMap<String, Object>();
        //
        for (int i = 1; i <= columnCount; i++) {
            data.put(rsmd.getColumnLabel(i), rs.getObject(rsmd.getColumnLabel(i)));
        }
        // ??MapList

        datas.add(data);
    }
    if (recordIndex != null && attribute != null) {
        String value = getAttributeRecord(datas, recordIndex, attribute);
        sb.append(value);
        sb.append("\n");
    }

    rs.close();
    prepareStatement.close();

    return sb.toString();
}

From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCwoTimeOutTestElement.java

/**
 * Gets a Data object from a ResultSet./*from ww  w . j  a  v  a  2s  . c  om*/
 *
 * @param rs
 *            ResultSet passed in from a database query
 * @return a Data object
 * @throws java.sql.SQLException
 * @throws UnsupportedEncodingException
 */
private String getStringFromResultSet(final ResultSet rs) throws SQLException, UnsupportedEncodingException {
    final ResultSetMetaData meta = rs.getMetaData();

    final StringBuilder sb = new StringBuilder();

    final int numColumns = meta.getColumnCount();
    for (int i = 1; i <= numColumns; i++) {
        sb.append(meta.getColumnLabel(i));
        if (i == numColumns) {
            sb.append('\n');
        } else {
            sb.append('\t');
        }
    }

    final JMeterVariables jmvars = getThreadContext().getVariables();
    final String varnames[] = getVariableNames().split(COMMA);
    final String resultVariable = getResultVariable().trim();
    List<Map<String, Object>> results = null;
    if (resultVariable.length() > 0) {
        results = new ArrayList<Map<String, Object>>();
        jmvars.putObject(resultVariable, results);
    }
    int j = 0;
    while (rs.next()) {
        Map<String, Object> row = null;
        j++;
        for (int i = 1; i <= numColumns; i++) {
            Object o = rs.getObject(i);
            if (results != null) {
                if (row == null) {
                    row = new HashMap<String, Object>(numColumns);
                    results.add(row);
                }
                row.put(meta.getColumnLabel(i), o);
            }
            if (o instanceof byte[]) {
                o = new String((byte[]) o, ENCODING);
            }
            sb.append(o);
            if (i == numColumns) {
                sb.append('\n');
            } else {
                sb.append('\t');
            }
            if (i <= varnames.length) { // i starts at 1
                final String name = varnames[i - 1].trim();
                if (name.length() > 0) { // Save the value in the variable if present
                    jmvars.put(name + UNDERSCORE + j, o == null ? null : o.toString());
                }
            }
        }
    }
    // Remove any additional values from previous sample
    for (int i = 0; i < varnames.length; i++) {
        final String name = varnames[i].trim();
        if (name.length() > 0 && jmvars != null) {
            final String varCount = name + "_#"; // $NON-NLS-1$
            // Get the previous count
            final String prevCount = jmvars.get(varCount);
            if (prevCount != null) {
                final int prev = Integer.parseInt(prevCount);
                for (int n = j + 1; n <= prev; n++) {
                    jmvars.remove(name + UNDERSCORE + n);
                }
            }
            jmvars.put(varCount, Integer.toString(j)); // save the current count
        }
    }

    return sb.toString();
}

From source file:com.hexin.core.dao.BaseDaoSupport.java

@Override
public <T> List<T> findListWithBlob(String sql, Class<T> dtoClass, Object... args)
        throws SQLException, InstantiationException, IllegalAccessException, SecurityException,
        IllegalArgumentException, NoSuchFieldException, IOException {

    long startTime = System.currentTimeMillis();
    long endTime;
    long durTime;

    debugSql(sql, args);//from ww w. j  a  v a2 s  .  co  m

    PreparedStatement ps = jdbcTemplate.getDataSource().getConnection().prepareStatement(sql);

    setPreparedStatementParameter(ps, args);

    List<T> list = new ArrayList<T>();
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();

        T obj = dtoClass.newInstance();
        for (int i = 1; i <= colCount; i++) {
            String colName = rsmd.getColumnLabel(i); // ??
            String colTypeName = rsmd.getColumnTypeName(i);
            String beanFiledName = IcpObjectUtil.underlineToCamel(colName);

            if ("blob".equalsIgnoreCase(colTypeName)) {
                InjectValueUtil.setFieldValue(obj, beanFiledName, rs.getBlob(i));
            } else {
                InjectValueUtil.setFieldValue(obj, beanFiledName, rs.getObject(i));
            }
        }

        list.add(obj);
    }

    endTime = System.currentTimeMillis();
    durTime = endTime - startTime;
    logger.debug("This jdbc operation costs time: " + durTime);

    return list;
}

From source file:org.apache.hadoop.hive.jdbc.storagehandler.AtsdDBRecordReader.java

private ResultSet replaceDotsInColumnNames(ResultSet resultSet) throws SQLException {
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();

    if (columnCount > 0) {
        CachedRowSetImpl crs = new CachedRowSetImpl();
        crs.populate(resultSet);//from  w w  w.  j a  v  a 2 s  .c om

        RowSetMetaDataImpl rwsm = new RowSetMetaDataImpl();

        rwsm.setColumnCount(columnCount);

        for (int i = 1; i <= columnCount; i++) {
            String columnName = metaData.getColumnName(i);
            if (columnName.contains(".")) {
                columnName = columnName.replaceAll("\\.", "\\$");
            }
            rwsm.setColumnName(i, columnName);
            rwsm.setColumnLabel(i, metaData.getColumnLabel(i));
            rwsm.setCatalogName(i, metaData.getCatalogName(i));
            rwsm.setColumnType(i, metaData.getColumnType(i));
            rwsm.setColumnTypeName(i, metaData.getColumnTypeName(i));
            rwsm.setSchemaName(i, metaData.getSchemaName(i));
            rwsm.setTableName(i, metaData.getTableName(i));
        }
        crs.setMetaData(rwsm);
        return crs;
    }
    return resultSet;
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java

private void buildFormatterAndNamesArray(ResultSetMetaData rsm,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    fFormatters = new FieldFormatter[rsm.getColumnCount() + 1];
    colNames = new String[rsm.getColumnCount() + 1];

    for (int i = 1; i < fFormatters.length; i++) {
        String cName = rsm.getColumnLabel(i);
        if (cName == null) {
            cName = rsm.getColumnName(i);
        }/*from w  w w . j av  a  2s  . c  o m*/
        colNames[i] = adaptName(cName);
        FieldFormatter fF = fieldNameToFormatter.get(cName);
        if (fF == null) {
            fF = fieldIdToFormatter.get("" + i);
        }
        fFormatters[i] = fF;
    }
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

/**
 * Verify that even with an empty ResultSet; the resultset meta-data can still
 * be queried. Previously, this was <i>Issue 75</i>.
 *//*from   w  w  w . ja  v a2  s  .  c o  m*/
@Test
public void testEmptyResultSet() throws Exception {

    Statement stmt = con.createStatement();

    String truncate = "TRUNCATE regressiontest;";
    stmt.execute(truncate);

    String select = "select ivalue from " + TABLE;

    ResultSet result = stmt.executeQuery(select);
    assertFalse("Make sure we have no rows", result.next());
    ResultSetMetaData rsmd = result.getMetaData();
    assertTrue("Make sure we do get a result", rsmd.getColumnDisplaySize(1) != 0);
    assertNotNull("Make sure we do get a label", rsmd.getColumnLabel(1));
    System.out.println(
            "Found a column in ResultsetMetaData even when there are no rows:   " + rsmd.getColumnLabel(1));
    stmt.close();
}