Example usage for java.sql ResultSetMetaData getColumnCount

List of usage examples for java.sql ResultSetMetaData getColumnCount

Introduction

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

Prototype

int getColumnCount() throws SQLException;

Source Link

Document

Returns the number of columns in this ResultSet object.

Usage

From source file:com.splicemachine.homeless.TestUtils.java

private static Map<String, Object> resultSetToOrderedMap(ResultSet rs) throws SQLException {
    Map<String, Object> result = new LinkedHashMap<>();
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();

    for (int i = 1; i <= cols; i++) {
        result.put(rsmd.getColumnName(i), rs.getObject(i));
    }/* w ww. j  a v  a 2  s . c  om*/

    return result;
}

From source file:com.tesora.dve.client.ClientTestNG.java

private static void verifyMetadata(ResultSetMetaData rsmd, String[] namesAndAliases) throws SQLException {
    if (namesAndAliases == null) {
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            System.out.println(rsmd.getColumnName(i) + " as " + rsmd.getColumnLabel(i));
        }//from   w ww.  j  a  v a 2s . c  om
        return;
    }
    int ncolumns = namesAndAliases.length / 2;
    assertEquals(ncolumns, rsmd.getColumnCount());
    for (int i = 0; i < ncolumns; i++) {
        String ename = namesAndAliases[2 * i];
        String ealias = namesAndAliases[2 * i + 1];
        assertEquals(ename, rsmd.getColumnName(i + 1));
        assertEquals(ealias, rsmd.getColumnLabel(i + 1));
    }
}

From source file:com.hangum.tadpole.engine.sql.util.resultset.ResultSetUtils.java

/**
 * ? table name/*from ww w . j a  v  a  2  s  . com*/
 * 
 * @param isShowRowNum
 * @param rs
 * @return
 * @throws Exception
 */
public static Map<Integer, String> getColumnTableName(final UserDBDAO userDB, boolean isShowRowNum,
        ResultSet rs) throws Exception {
    Map<Integer, String> mapColumnName = new HashMap<Integer, String>();
    int intStartIndex = 0;

    if (isShowRowNum) {
        intStartIndex++;
        mapColumnName.put(0, "#");
    }

    ResultSetMetaData rsm = rs.getMetaData();
    for (int i = 0; i < rsm.getColumnCount(); i++) {
        //         if(userDB.getDBDefine() == DBDefine.POSTGRE_DEFAULT) {
        //            PGResultSetMetaData pgsqlMeta = (PGResultSetMetaData)rsm;
        //            mapColumnName.put(i+intStartIndex, pgsqlMeta.getBaseTableName(i+1));
        //            
        ////            if(logger.isDebugEnabled()) logger.debug("Table name is " + pgsqlMeta.getBaseTableName(i+1));
        //         } else
        if (userDB.getDBDefine() == DBDefine.HIVE_DEFAULT || userDB.getDBDefine() == DBDefine.HIVE2_DEFAULT) {
            mapColumnName.put(i + intStartIndex, "Apache Hive is not support this method.");
        } else {
            if (rsm.getSchemaName(i + 1) == null || "".equals(rsm.getSchemaName(i + 1))) {
                //               if(logger.isDebugEnabled()) logger.debug("Table name is " + rsm.getTableName(i+1) + ", schema name is " + rsm.getSchemaName(i+1));

                mapColumnName.put(i + intStartIndex, rsm.getTableName(i + 1));
            } else {
                mapColumnName.put(i + intStartIndex, rsm.getSchemaName(i + 1) + "." + rsm.getTableName(i + 1));
            }
        }
    }

    return mapColumnName;
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Returns next record of result set as a Map.
 * The keys of the map are the column names,
 * as returned by the metadata.//from   w w w .  j av a2 s  .c o  m
 * The values are the columns as Objects.
 *
 * @param resultSet The ResultSet to process.
 * @exception SQLException if an error occurs.
 */
public static Map getMap(ResultSet resultSet) throws SQLException {

    // Acquire resultSet MetaData
    ResultSetMetaData metaData = resultSet.getMetaData();
    int cols = metaData.getColumnCount();

    // Create hashmap, sized to number of columns
    HashMap row = new HashMap(cols, 1);

    // Transfer record into hashmap
    if (resultSet.next()) {
        for (int i = 1; i <= cols; i++) {
            row.put(metaData.getColumnName(i), resultSet.getObject(i));
        }
    } // end while

    return ((Map) row);

}

From source file:AIR.Common.DB.AbstractDLL.java

public static boolean hasColumn(ResultSet reader, String columnName) throws SQLException {
    ResultSetMetaData metaData = reader.getMetaData();
    for (int i = 1; i <= metaData.getColumnCount(); ++i) {
        if ((metaData.getColumnName(i).equals(columnName))) {
            return true;
        }/*from  w w  w  .  j  ava 2 s  .c  om*/
    }
    return false;
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Return a Collection of Maps, each representing
 * a row from the ResultSet.//  ww w  .jav a2s .  c o m
 * The keys of the map are the column names,
 * as returned by the metadata.
 * The values are the columns as Objects.
 *
 * @param resultSet The ResultSet to process.
 * @exception SQLException if an error occurs.
 */
public static Collection getMaps(ResultSet resultSet) throws SQLException {

    // Acquire resultSet MetaData
    ResultSetMetaData metaData = resultSet.getMetaData();
    int cols = metaData.getColumnCount();

    // Use ArrayList to maintain ResultSet sequence
    ArrayList list = new ArrayList();

    // Scroll to each record, make map of row, add to list
    while (resultSet.next()) {
        HashMap row = new HashMap(cols, 1);
        for (int i = 1; i <= cols; i++) {
            row.put(metaData.getColumnName(i), resultSet.getString(i));
        }
        list.add(row);
    } // end while

    return ((Collection) list);

}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Populate target bean with the first record from a ResultSet.
 *
 * @param resultSet The ResultSet whose parameters are to be used
 * to populate bean properties/*from w  ww . java  2 s.  c o m*/
 * @param target An instance of the bean to populate
 * @exception SQLException if an exception is thrown while setting
 * property values, populating the bean, or accessing the ResultSet
 * @return True if resultSet contained a next element
 */
public static boolean getElement(Object target, ResultSet resultSet) throws Exception {

    // Check prerequisites
    if ((target == null) || (resultSet == null))
        throw new SQLException("getElement: Null parameter");

    // Acquire resultSet MetaData
    ResultSetMetaData metaData = resultSet.getMetaData();
    int cols = metaData.getColumnCount();

    // Create hashmap, sized to number of columns
    HashMap properties = new HashMap(cols, 1);

    // Scroll to next record and pump into hashmap
    boolean found = false;
    if (resultSet.next()) {
        found = true;
        for (int i = 1; i <= cols; i++) {
            putEntry(properties, metaData, resultSet, i, target.getClass());
        }
        // try {
        BeanUtils.copyProperties(target, properties);
        //analyseRelationships(target);
        //  }
        // catch (Throwable t) {
        // throw new SQLException("ResultSetUtils.getElement: " +
        //     t.getMessage() + " - " + properties.toString());
        //}

    } // end if

    return found;

}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Return a ArrayList of beans populated from a ResultSet.
 *
 * @param resultSet The ResultSet whose parameters are to be used
 * to populate bean properties/*w ww.  jav a  2  s .co m*/
 * @param target An instance of the bean to populate
 * @exception SQLException if an exception is thrown while setting
 * property values, populating the bean, or accessing the ResultSet
 */
public static Collection getCollection(Object target, ResultSet resultSet) throws Exception {

    // Check prerequisites
    if ((target == null) || (resultSet == null))
        throw new GenericDAOException("getCollection: Null parameter");

    // Acquire resultSet MetaData
    ResultSetMetaData metaData = resultSet.getMetaData();
    int cols = metaData.getColumnCount();

    // Create hashmap, sized to number of columns
    HashMap properties = new HashMap(cols, 1);

    // Use ArrayList to maintain ResultSet sequence
    ArrayList list = new ArrayList();

    // Acquire target class
    Class factory = target.getClass();

    // Scroll to next record and pump into hashmap
    while (resultSet.next()) {
        for (int i = 1; i <= cols; i++) {
            putEntry(properties, metaData, resultSet, i, target.getClass());
        }
        Object bean = factory.newInstance();
        BeanUtils.copyProperties(bean, properties);
        list.add(bean);
        properties.clear();

    } // end while

    return ((Collection) list);

}

From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java

/**
 * Creates an Avro schema from a result set. If the table/record name is known a priori and provided, use that as a
 * fallback for the record name if it cannot be retrieved from the result set, and finally fall back to a default value.
 *
 * @param rs         The result set to convert to Avro
 * @param recordName The a priori record name to use if it cannot be determined from the result set.
 * @return A Schema object representing the result set converted to an Avro record
 * @throws SQLException if any error occurs during conversion
 *///from w  ww.ja v a 2 s.c o m
public static Schema createSchema(final ResultSet rs, String recordName, boolean convertNames)
        throws SQLException {
    final ResultSetMetaData meta = rs.getMetaData();
    final int nrOfColumns = meta.getColumnCount();
    String tableName = StringUtils.isEmpty(recordName) ? "NiFi_ExecuteSQL_Record" : recordName;
    if (nrOfColumns > 0) {
        String tableNameFromMeta = meta.getTableName(1);
        if (!StringUtils.isBlank(tableNameFromMeta)) {
            tableName = tableNameFromMeta;
        }
    }

    if (convertNames) {
        tableName = normalizeNameForAvro(tableName);
    }

    final FieldAssembler<Schema> builder = SchemaBuilder.record(tableName).namespace("any.data").fields();

    /**
     * Some missing Avro types - Decimal, Date types. May need some additional work.
     */
    for (int i = 1; i <= nrOfColumns; i++) {
        /**
        *   as per jdbc 4 specs, getColumnLabel will have the alias for the column, if not it will have the column name.
        *  so it may be a better option to check for columnlabel first and if in case it is null is someimplementation,
        *  check for alias. Postgres is the one that has the null column names for calculated fields.
        */
        String nameOrLabel = StringUtils.isNotEmpty(meta.getColumnLabel(i)) ? meta.getColumnLabel(i)
                : meta.getColumnName(i);
        String columnName = convertNames ? normalizeNameForAvro(nameOrLabel) : nameOrLabel;
        switch (meta.getColumnType(i)) {
        case CHAR:
        case LONGNVARCHAR:
        case LONGVARCHAR:
        case NCHAR:
        case NVARCHAR:
        case VARCHAR:
        case CLOB:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        case BIT:
        case BOOLEAN:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().booleanType().endUnion()
                    .noDefault();
            break;

        case INTEGER:
            if (meta.isSigned(i)) {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion()
                        .noDefault();
            } else {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion()
                        .noDefault();
            }
            break;

        case SMALLINT:
        case TINYINT:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion()
                    .noDefault();
            break;

        case BIGINT:
            // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that.
            // If the precision > 19 (or is negative), use a string for the type, otherwise use a long. The object(s) will be converted
            // to strings as necessary
            int precision = meta.getPrecision(i);
            if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                        .noDefault();
            } else {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion()
                        .noDefault();
            }
            break;

        // java.sql.RowId is interface, is seems to be database
        // implementation specific, let's convert to String
        case ROWID:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        case FLOAT:
        case REAL:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().floatType().endUnion()
                    .noDefault();
            break;

        case DOUBLE:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion()
                    .noDefault();
            break;

        // Did not find direct suitable type, need to be clarified!!!!
        case DECIMAL:
        case NUMERIC:
            int scale = meta.getScale(i);
            if (scale == 0) {
                if (meta.getPrecision(i) < 10) {
                    builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion()
                            .noDefault();
                } else {
                    builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType()
                            .endUnion().noDefault();
                }
            } else {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion()
                        .noDefault();
            }
            break;

        // Did not find direct suitable type, need to be clarified!!!!
        case DATE:
        case TIME:
        case TIMESTAMP:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        case BINARY:
        case VARBINARY:
        case LONGVARBINARY:
        case ARRAY:
        case BLOB:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().bytesType().endUnion()
                    .noDefault();
            break;

        default:
            throw new IllegalArgumentException("createSchema: Unknown SQL type " + meta.getColumnType(i)
                    + " cannot be converted to Avro type");
        }
    }

    return builder.endRecord();
}

From source file:TerminalMonitor.java

static public void processResults(ResultSet results) throws SQLException {
    try {/* w w w  .jav  a  2  s. com*/
        ResultSetMetaData meta = results.getMetaData();
        StringBuffer bar = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        int cols = meta.getColumnCount();
        int row_count = 0;
        int i, width = 0;

        // Prepare headers for each of the columns
        // The display should look like:
        //  --------------------------------------
        //  | Column One | Column Two |
        //  --------------------------------------
        //  | Row 1 Value | Row 1 Value |
        //  --------------------------------------

        // create the bar that is as long as the total of all columns
        for (i = 1; i <= cols; i++) {
            width += meta.getColumnDisplaySize(i);
        }
        width += 1 + cols;
        for (i = 0; i < width; i++) {
            bar.append('-');
        }
        bar.append('\n');
        buffer.append(bar.toString() + "|");
        // After the first bar goes the column labels
        for (i = 1; i <= cols; i++) {
            StringBuffer filler = new StringBuffer();
            String label = meta.getColumnLabel(i);
            int size = meta.getColumnDisplaySize(i);
            int x;

            // If the label is longer than the column is wide,
            // then we truncate the column label
            if (label.length() > size) {
                label = label.substring(0, size);
            }
            // If the label is shorter than the column, pad it with spaces
            if (label.length() < size) {
                int j;

                x = (size - label.length()) / 2;
                for (j = 0; j < x; j++) {
                    filler.append(' ');
                }
                label = filler + label + filler;
                if (label.length() > size) {
                    label = label.substring(0, size);
                } else {
                    while (label.length() < size) {
                        label += " ";
                    }
                }
            }
            // Add the column header to the buffer
            buffer.append(label + "|");
        }
        // Add the lower bar
        buffer.append("\n" + bar.toString());
        // Format each row in the result set and add it on
        while (results.next()) {
            row_count++;

            buffer.append('|');
            // Format each column of the row
            for (i = 1; i <= cols; i++) {
                StringBuffer filler = new StringBuffer();
                Object value = results.getObject(i);
                int size = meta.getColumnDisplaySize(i);
                String str;

                if (results.wasNull()) {
                    str = "NULL";
                } else {
                    str = value.toString();
                }
                if (str.length() > size) {
                    str = str.substring(0, size);
                }
                if (str.length() < size) {
                    int j, x;

                    x = (size - str.length()) / 2;
                    for (j = 0; j < x; j++) {
                        filler.append(' ');
                    }
                    str = filler + str + filler;
                    if (str.length() > size) {
                        str = str.substring(0, size);
                    } else {
                        while (str.length() < size) {
                            str += " ";
                        }
                    }
                }
                buffer.append(str + "|");
            }
            buffer.append("\n");
        }
        // Stick a row count up at the top
        if (row_count == 0) {
            buffer = new StringBuffer("No rows selected.\n");
        } else if (row_count == 1) {
            buffer = new StringBuffer("1 row selected.\n" + buffer.toString() + bar.toString());
        } else {
            buffer = new StringBuffer(row_count + " rows selected.\n" + buffer.toString() + bar.toString());
        }
        System.out.print(buffer.toString());
        System.out.flush();
    } catch (SQLException e) {
        throw e;
    } finally {
        try {
            results.close();
        } catch (SQLException e) {
        }
    }
}