Example usage for java.sql ResultSetMetaData getColumnType

List of usage examples for java.sql ResultSetMetaData getColumnType

Introduction

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

Prototype

int getColumnType(int column) throws SQLException;

Source Link

Document

Retrieves the designated column's SQL type.

Usage

From source file:org.protempa.backend.dsb.relationaldb.EventResultProcessor.java

@Override
public void process(ResultSet resultSet) throws SQLException {
    ResultCache<Event> results = getResults();
    EntitySpec entitySpec = getEntitySpec();
    String entitySpecName = entitySpec.getName();
    //boolean hasRefs = entitySpec.getInboundRefSpecs().length > 0;
    String[] propIds = entitySpec.getPropositionIds();
    ColumnSpec codeSpec = entitySpec.getCodeSpec();
    if (codeSpec != null) {
        List<ColumnSpec> codeSpecL = codeSpec.asList();
        codeSpec = codeSpecL.get(codeSpecL.size() - 1);
    }// www.java  2s .c  om
    Logger logger = SQLGenUtil.logger();
    PropertySpec[] propertySpecs = entitySpec.getPropertySpecs();
    Value[] propertyValues = new Value[propertySpecs.length];
    int count = 0;
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    int[] columnTypes = new int[resultSetMetaData.getColumnCount()];
    for (int i = 0; i < columnTypes.length; i++) {
        columnTypes[i] = resultSetMetaData.getColumnType(i + 1);
    }
    String[] uniqueIds = new String[entitySpec.getUniqueIdSpecs().length];
    SourceSystem dsType = DataSourceBackendSourceSystem.getInstance(getDataSourceBackendId());
    JDBCPositionFormat positionParser = entitySpec.getPositionParser();

    while (resultSet.next()) {
        int i = 1;
        String keyId = resultSet.getString(i++);
        if (keyId == null) {
            logger.warning("A keyId is null. Skipping record.");
            continue;
        }

        i = readUniqueIds(uniqueIds, resultSet, i);
        if (Arrays.contains(uniqueIds, null)) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.log(Level.WARNING, "Unique ids contain null ({0}). Skipping record.",
                        StringUtils.join(uniqueIds, ", "));
                continue;
            }
        }
        UniqueId uniqueId = generateUniqueId(entitySpecName, uniqueIds);

        String propId = null;
        if (!isCasePresent()) {
            if (codeSpec == null) {
                assert propIds.length == 1 : "Don't know which proposition id to assign to";
                propId = propIds[0];
            } else {
                String code = resultSet.getString(i++);
                propId = sqlCodeToPropositionId(codeSpec, code);
                if (propId == null) {
                    continue;
                }
            }
        } else {
            i++;
        }

        ColumnSpec finishTimeSpec = entitySpec.getFinishTimeSpec();
        Granularity gran = entitySpec.getGranularity();
        Interval interval = null;
        if (finishTimeSpec == null) {
            Long d = null;
            try {
                d = positionParser.toPosition(resultSet, i, columnTypes[i - 1]);
                i++;
            } catch (SQLException e) {
                logger.log(Level.WARNING, "Could not parse timestamp. Leaving the start time/timestamp unset.",
                        e);
            }
            interval = intervalFactory.getInstance(d, gran);
        } else {
            Long start = null;
            try {
                start = positionParser.toPosition(resultSet, i, columnTypes[i - 1]);
            } catch (SQLException e) {
                logger.log(Level.WARNING, "Could not parse start time. Leaving the start time/timestamp unset.",
                        e);
            } finally {
                i++;
            }
            Long finish = null;
            try {
                finish = positionParser.toPosition(resultSet, i, columnTypes[i - 1]);
            } catch (SQLException e) {
                logger.log(Level.WARNING, "Could not parse start time. Leaving the finish time unset.", e);
            } finally {
                i++;
            }
            if (finish != null && start != null && finish.compareTo(start) < 0) {
                logger.log(Level.WARNING, "Finish {0} is before start {1}: Leaving time unset",
                        new Object[] { finish, start });
                interval = intervalFactory.getInstance(null, gran, null, gran);
            } else {
                interval = intervalFactory.getInstance(start, gran, finish, gran);
            }
        }

        i = extractPropertyValues(resultSet, i, propertyValues, columnTypes);

        if (isCasePresent()) {
            propId = resultSet.getString(i++);
        }

        Event event = new Event(propId, uniqueId);
        event.setSourceSystem(dsType);
        event.setInterval(interval);
        for (int j = 0; j < propertySpecs.length; j++) {
            PropertySpec propertySpec = propertySpecs[j];
            event.setProperty(propertySpec.getName(), propertyValues[j]);
        }
        logger.log(Level.FINEST, "Created event {0}", event);
        results.add(keyId, event);
        if (++count % FLUSH_SIZE == 0) {
            try {
                results.flush(this);
            } catch (IOException ex) {
                throw new QueryResultsCacheException("Flushing primitive parameters to cache failed", ex);
            }
            if (logger.isLoggable(Level.FINE)) {
                Logging.logCount(logger, Level.FINE, count, "Retrieved {0} record", "Retrieved {0} records");
            }
        }
    }
    try {
        results.flush(this);
    } catch (IOException ex) {
        throw new QueryResultsCacheException("Flushing primitive parameters to cache failed", ex);
    }
    if (logger.isLoggable(Level.FINE)) {
        Logging.logCount(logger, Level.FINE, count, "Retrieved {0} record total",
                "Retrieved {0} records total");
    }
}

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

public void fillReportFromMetaData(TabularReport report) throws SQLException {
    ResultSetMetaData rsmd = resultSet.getMetaData();
    int numColumns = rsmd.getColumnCount();

    TabularReportColumns columns = report.getColumns();
    columns.clear();/*from   w ww.j a v  a2 s .com*/

    for (int c = 1; c <= numColumns; c++) {
        TabularReportColumn column = null;

        int dataType = rsmd.getColumnType(c);
        switch (dataType) {
        case Types.INTEGER:
        case Types.SMALLINT:
        case Types.BIGINT:
        case Types.TINYINT:
        case Types.BIT:
            column = new NumericColumn();
            break;

        case Types.FLOAT:
        case Types.REAL:
            column = new DecimalColumn();
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
            if (rsmd.getScale(c) > 0)
                column = new DecimalColumn();
            else
                column = new NumericColumn();
            break;

        default:
            column = new GeneralColumn();
            break;
        }

        column.setColIndex(c - 1);
        column.setHeading(new StaticValueSource(
                TextUtils.getInstance().sqlIdentifierToText(rsmd.getColumnLabel(c), true)));
        column.setDataType(dataType);
        column.setWidth(rsmd.getColumnDisplaySize(c));

        columns.add(column);
    }

    report.finalizeContents();
}

From source file:org.apache.sqoop.connector.jdbc.GenericJdbcToInitializer.java

@Override
public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig,
        ToJobConfiguration toJobConfig) {
    configureJdbcProperties(context.getContext(), linkConfig, toJobConfig);

    String schemaName = toJobConfig.toJobConfig.tableName;

    if (schemaName == null) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0019,
                "Table name extraction not supported yet.");
    }/* w w  w  .  j  a  v a2 s .  co  m*/

    if (toJobConfig.toJobConfig.schemaName != null) {
        schemaName = toJobConfig.toJobConfig.schemaName + "." + schemaName;
    }

    Schema schema = new Schema(schemaName);
    ResultSet rs = null;
    ResultSetMetaData rsmt = null;
    try {
        rs = executor.executeQuery("SELECT * FROM " + schemaName + " WHERE 1 = 0");

        rsmt = rs.getMetaData();
        for (int i = 1; i <= rsmt.getColumnCount(); i++) {
            Column column = SqlTypesUtils.sqlTypeToAbstractType(rsmt.getColumnType(i));

            String columnName = rsmt.getColumnName(i);
            if (columnName == null || columnName.equals("")) {
                columnName = rsmt.getColumnLabel(i);
                if (null == columnName) {
                    columnName = "Column " + i;
                }
            }

            column.setName(columnName);
            schema.addColumn(column);
        }

        return schema;
    } catch (SQLException e) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.info("Ignoring exception while closing ResultSet", e);
            }
        }
    }
}

From source file:de.ufinke.cubaja.sql.ObjectFactoryGenerator.java

private void createSearchMap(ResultSetMetaData metaData) throws SQLException {

    int size = metaData.getColumnCount();

    searchMap = new HashMap<String, SearchEntry>();

    for (int i = 1; i <= size; i++) {
        String name = metaData.getColumnName(i).toLowerCase();
        SearchEntry entry = new SearchEntry(name, i, metaData.getColumnType(i));
        searchMap.put(Util.createMethodName(name, "set"), entry);
    }/*from w  w  w.ja  v  a  2s. c  o  m*/

    if (searchMap.size() == 1) {
        singleColumnSqlType = metaData.getColumnType(1);
    }
}

From source file:com.taobao.tddl.common.jdbc.MetaDataQueryForMapHandler.java

/**
 * @param tableName /*from  w  ww. ja  va 2s  .co m*/
 */
private void initMetaData(String tableName, ResultSetMetaData rsmd) {
    try {
        int columnCount = rsmd.getColumnCount();
        String[] columnNames = new String[columnCount];
        ColumnMetaData[] columns = new ColumnMetaData[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columnNames[i - 1] = rsmd.getColumnName(i).toLowerCase();
            int sqlType = rsmd.getColumnType(i);
            if (sqlType == java.sql.Types.DATE) {
                sqlType = java.sql.Types.TIMESTAMP;
            }
            int scale = rsmd.getScale(i);
            String className = rsmd.getColumnClassName(i);
            columns[i - 1] = new ColumnMetaData(sqlType, scale, className);
        }
        TableMetaData tmd = new TableMetaData(columnNames, columns);
        this.tableMetaDatas.putIfAbsent(tableName, tmd);
    } catch (SQLException e) {
        log.warn("Fetch Metadata from resultSet failed.", e);
    }
}

From source file:be.bittich.dynaorm.repository.GenericDynaRepository.java

/**
 * Configuration/*  w  w  w.  j  av a2s  .  co m*/
 */
private void configure() {
    runner = getQueryRunner();
    dialect = getDialect();
    // default tableName
    TableFromDB table = AnnotationProcessor.getAnnotationType(clazz, TableFromDB.class);
    String tableName = clazz.getSimpleName().toLowerCase();
    if (table != null && !isEmpty(table.tableName())) {
        tableName = table.tableName();
    }
    tableColumn = new TableColumn(tableName);
    rowProcessor = new DynaRowProcessor(tableColumn);
    try {
        ResultSet rs = runner.getDataSource().getConnection()
                .prepareStatement(dialect.requestForTableColumns(tableName)).executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        Integer nbColumns = metaData.getColumnCount();
        for (int i = 1; i <= nbColumns; i++) {
            String name = metaData.getColumnName(i);
            int type = metaData.getColumnType(i);
            tableColumn.addColumn(name, type);
        }
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:org.jfree.data.jdbc.JDBCPieDataset.java

/**
 *  ExecuteQuery will attempt execute the query passed to it against the
 *  existing database connection.  If no connection exists then no action
 *  is taken./*  www  .  ja  v a 2  s.c  om*/
 *  The results from the query are extracted and cached locally, thus
 *  applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed
 * @param  con  the connection the query is to be executed against
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;

    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();
        if (columnCount != 2) {
            throw new SQLException("Invalid sql generated.  PieDataSet requires 2 columns only");
        }

        int columnType = metaData.getColumnType(2);
        double value = Double.NaN;
        while (resultSet.next()) {
            Comparable key = resultSet.getString(1);
            switch (columnType) {
            case Types.NUMERIC:
            case Types.REAL:
            case Types.INTEGER:
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.DECIMAL:
            case Types.BIGINT:
                value = resultSet.getDouble(2);
                setValue(key, value);
                break;

            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                Timestamp date = resultSet.getTimestamp(2);
                value = date.getTime();
                setValue(key, value);
                break;

            default:
                System.err.println("JDBCPieDataset - unknown data type");
                break;
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info

    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
    }
}

From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java

/**
 * The method prepares table's data in the shape and passes every {@link Row} into given RowProcessor.
 * /*w  w w .  j a v  a2  s.c om*/
 * @param processor
 *            injected logic to perform some actions under passing rows. see details for {@link RowProcessor}.
 * @throws SQLException
 *             if any errors during work with database occur.
 */
public void getData(final RowProcessor processor) throws SQLException {
    try {
        jdbcTemplate.query(SELECT_FROM + tableName, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();

                Row row = new Row();
                for (int i = 1; i <= columnCount; i++) {
                    ColumnMetaData columnMetaData = ColumnMetaData.getInstance(metaData.getColumnName(i),
                            SqlTypes.getSqlTypeByJdbcSqlType(metaData.getColumnType(i)));
                    row.addCell(columnMetaData, rs.getObject(i));
                }
                try {
                    processor.process(row);
                } catch (RowProcessingException e) {
                    throw new SQLException(e);
                }
            }
        });

    } catch (DataAccessException e) {
        throw new SQLException(e);
    }
}

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View resutls of a {@link ResultSet}./*from   w  ww .j a v a2s  .com*/
 * 
 * @param resultSet
 * @throws SQLException 
 */
public void viewResult(ResultSet resultSet) throws SQLException {
    if (resultSet == null) {
        // nothing to do
        return;
    }

    // collect the meta
    ResultSetMetaData meta = resultSet.getMetaData();

    final int numColumns = meta.getColumnCount();
    final int[] displaySizes = new int[numColumns + 1];
    final int[] colType = new int[numColumns + 1];

    for (int index = 1; index <= numColumns; index++) {
        colType[index] = meta.getColumnType(index);
        displaySizes[index] = getColumnSize(meta.getTableName(index), meta.getColumnName(index),
                colType[index]);
    }

    // display the header row
    for (int index = 1; index <= numColumns; index++) {
        center(meta.getColumnLabel(index), displaySizes[index]);
    }
    System.out.println("|");
    for (int index = 1; index <= numColumns; index++) {
        System.out.print("+" + StringUtils.repeat('-', displaySizes[index] + 2));
    }
    System.out.println("+");

    // start iterating over the result set
    int rowsDisplayed = 0;
    int numRecords = 0;
    while (resultSet.next()) {
        // read and display the value
        rowsDisplayed++;
        numRecords++;

        for (int index = 1; index <= numColumns; index++) {
            switch (colType[index]) {
            case Types.DECIMAL:
            case Types.DOUBLE:
            case Types.REAL:
                format(resultSet.getDouble(index), displaySizes[index]);
                continue;

            case Types.INTEGER:
            case Types.SMALLINT:
                format(resultSet.getInt(index), displaySizes[index]);
                continue;

            case Types.VARCHAR:
                format(resultSet.getString(index), displaySizes[index], false);
                continue;

            case Types.TIMESTAMP:
                format(resultSet.getTimestamp(index), displaySizes[index]);
                continue;

            case Types.BIGINT:
                format(resultSet.getBigDecimal(index), displaySizes[index]);
                continue;
            }
        }

        // terminator for row and new line
        System.out.println("|");

        // check for rows displayed
        if (rowsDisplayed == 20) {
            // ask the user if more data needs to be displayed
            String cont = ConsoleUtils.readLine("Type \"it\" for more: ", true);
            if (!"it".equalsIgnoreCase(cont)) {
                break;
            }

            // continue;
            rowsDisplayed = 0;
            continue;
        }
    }

    System.out.println("\nTotal number of records found: " + numRecords);
}

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

public List<List<Column>> select(String sqlQuery, List<Column> queryParams) {
    Connection connection = null;
    try {/*  ww w .  j av a2s.  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);
    }
}