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:net.sf.jdbcwrappers.trim.TrimmingResultSetWrapper.java

private void fetchCharColumns() throws SQLException {
    if (charColumns == null) {
        ResultSetMetaData metadata = getMetaData();
        int columnCount = metadata.getColumnCount();
        charColumns = new HashSet<String>();
        isCharColumn = new boolean[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            if (metadata.getColumnType(i) == Types.CHAR) {
                charColumns.add(metadata.getColumnName(i).toUpperCase());
                isCharColumn[i - 1] = true;
            }/*from  w  w w  .  j  av  a2 s . c o  m*/
        }
        if (log.isDebugEnabled()) {
            log.debug("CHAR columns: " + charColumns);
        }
    }
}

From source file:jp.gr.java_conf.ka_ka_xyz.processor.AnnotationProcessor.java

@Override
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);
        for (int i = 0; i < props.length; i++) {
            if (equalsColumnAnnotation(columnName, props[i].getName())) {
                columnToProperty[col] = i;
                break;
            }//from   w w  w.jav a2s . c  o  m
        }
    }
    return columnToProperty;
}

From source file:com.dangdang.ddframe.rdb.sharding.jdbc.adapter.AbstractResultSetAdapter.java

private Map<String, Integer> generateColumnLabelIndexMap() throws SQLException {
    ResultSetMetaData resultSetMetaData = resultSets.get(0).getMetaData();
    Map<String, Integer> result = new CaseInsensitiveMap<>(resultSetMetaData.getColumnCount());
    for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
        result.put(resultSetMetaData.getColumnLabel(i), i);
    }/*from  w w w  .  java 2 s  .  c  o  m*/
    return result;
}

From source file:com.abixen.platform.service.businessintelligence.multivisualization.service.impl.JsonFilterServiceImpl.java

private Map<String, String> getColumnTypeMapping(ResultSetMetaData rsmd) throws SQLException {
    int columnCount = rsmd.getColumnCount();
    Map<String, String> columnTypeMapping = new HashMap<>();

    IntStream.range(1, columnCount + 1).forEach(i -> {
        try {//  w  w w .  j a  v  a 2 s.  c o  m
            String columnTypeName = rsmd.getColumnTypeName(i);
            if ("BIGINT".equals(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            if ("VARCHAR".equals(columnTypeName)) {
                columnTypeName = "STRING";
            }
            if ("FLOAT8".equals(columnTypeName)) {
                columnTypeName = "DOUBLE";
            }
            columnTypeMapping.put(rsmd.getColumnName(i).toUpperCase(), columnTypeName.toUpperCase());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    return columnTypeMapping;
}

From source file:com.gzj.tulip.jade.rowmapper.MapEntryColumnRowMapper.java

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

    // ?//  w  w w .  ja  va2s . co m
    if (rowNum == 0) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int nrOfColumns = rsmd.getColumnCount();
        if (nrOfColumns != 2) {
            throw new IncorrectResultSetColumnCountException(2, nrOfColumns);
        }

        if (StringUtils.isNotEmpty(keyColumn)) {
            keyColumnIndex = rs.findColumn(keyColumn);
            if (keyColumnIndex == 1) {
                valueColumnIndex = 2;
            } else if (keyColumnIndex == 2) {
                valueColumnIndex = 1;
            } else {
                throw new IllegalArgumentException(
                        String.format("wrong key name %s for method: %s ", keyColumn, modifier.getMethod()));
            }
            keyColumn = null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("keyIndex=%s; valueIndex=%s; for method: %s ", keyColumnIndex,
                    valueColumnIndex, modifier.getMethod()));
        }
    }

    //   JDBC ResultSet ?  Key
    Object key = JdbcUtils.getResultSetValue(rs, keyColumnIndex, keyType);
    if (key != null && !keyType.isInstance(key)) {
        ResultSetMetaData rsmd = rs.getMetaData();
        throw new TypeMismatchDataAccessException( // NL
                "Type mismatch affecting row number " + rowNum + " and column type '"
                        + rsmd.getColumnTypeName(keyColumnIndex) + "' expected type is '" + keyType + "'");
    }

    //   JDBC ResultSet ?  Value
    Object value = JdbcUtils.getResultSetValue(rs, valueColumnIndex, valueType);
    if (value != null && !valueType.isInstance(value)) {
        ResultSetMetaData rsmd = rs.getMetaData();
        throw new TypeMismatchDataAccessException( // NL
                "Type mismatch affecting row number " + rowNum + " and column type '"
                        + rsmd.getColumnTypeName(valueColumnIndex) + "' expected type is '" + valueType + "'");
    }

    // key?null??
    return new MapEntryImpl<Object, Object>(key, value);
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.application.service.JsonFilterService.java

private Map<String, String> getColumnTypeMapping(ResultSetMetaData rsmd) throws SQLException {
    int columnCount = rsmd.getColumnCount();
    Map<String, String> columnTypeMapping = new HashMap<>();

    IntStream.range(1, columnCount + 1).forEach(i -> {
        try {//from  w ww.  j  a  va2s .  c  o m
            String columnTypeName = rsmd.getColumnTypeName(i);
            if ("BIGINT".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            if ("VARCHAR".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "STRING";
            }
            if ("FLOAT8".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "DOUBLE";
            }
            if ("INT8".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            columnTypeMapping.put(rsmd.getColumnName(i).toUpperCase(), columnTypeName.toUpperCase());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    return columnTypeMapping;
}

From source file:annis.sqlgen.AnnotatedSpanExtractor.java

@Override
public AnnotatedSpan mapRow(ResultSet resultSet, int rowNum) throws SQLException {
    long id = resultSet.getLong("id");
    String coveredText = resultSet.getString("span");

    Array arrayAnnotation = resultSet.getArray("annotations");
    ResultSetMetaData rsMeta = resultSet.getMetaData();
    Array arrayMeta = null;//from   ww w  .j  ava2s  . c  o m
    for (int i = 1; i <= rsMeta.getColumnCount(); i++) {
        if ("metadata".equals(rsMeta.getColumnName(i))) {
            arrayMeta = resultSet.getArray(i);
            break;
        }
    }

    List<Annotation> annotations = extractAnnotations(arrayAnnotation);
    List<Annotation> metaData = arrayMeta == null ? new LinkedList<Annotation>()
            : extractAnnotations(arrayMeta);

    // create key
    Array sqlKey = resultSet.getArray("key");
    Validate.isTrue(!resultSet.wasNull(), "Match group identifier must not be null");
    Validate.isTrue(sqlKey.getBaseType() == Types.BIGINT,
            "Key in database must be from the type \"bigint\" but was \"" + sqlKey.getBaseTypeName() + "\"");

    List<Long> key = Arrays.asList((Long[]) sqlKey.getArray());

    return new AnnotatedSpan(id, coveredText, annotations, metaData, key);
}

From source file:com.pankaj.GenericResource.java

/**
 * Retrieves representation of an instance of com.pankaj.GenericResource
 *
 * @return an instance of java.lang.String
 * @throws java.lang.ClassNotFoundException
 * @throws java.sql.SQLException//from  w  ww.j a v  a  2 s .c  om
 * @throws java.lang.InstantiationException
 * @throws java.lang.IllegalAccessException
 */
@GET
@Path("/products")
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts()
        throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {

    Statement smt = conn.createStatement();
    ResultSet rs = smt.executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int col = rsmd.getColumnCount();
    while (rs.next()) {

        product pro = new product(rs.getInt("productid"), rs.getString("name"), rs.getString("description"),
                rs.getInt("quantity"));
        products.add(pro);

        json = Json.createObjectBuilder().add("productID", rs.getInt("productID"))
                .add("name", rs.getString("name")).add("description", rs.getString("description"))
                .add("quantity", rs.getInt("quantity"));
        productarray.add(json);
    }
    String res = productarray.build().toString();
    return res;
}

From source file:org.danann.cernunnos.sql.ColumnIteratorTask.java

public void perform(TaskRequest req, TaskResponse res) {
    ResultSetMetaData rsmd = (ResultSetMetaData) req.getAttribute(SqlAttributes.RESULT_SET_METADATA);

    final int columnCount;
    try {/*from  w  w w.ja  v a  2s  .c om*/
        columnCount = rsmd.getColumnCount();
    } catch (SQLException sqle) {
        throw SQL_EXCEPTION_TRANSLATOR.translate("Failed to get column count from ResultSetMetaData", "UNKNOWN",
                sqle);
    }

    for (int i = 1; i <= columnCount; i++) {
        final String columnName;
        try {
            columnName = rsmd.getColumnLabel(i);
        } catch (SQLException sqle) {
            throw SQL_EXCEPTION_TRANSLATOR
                    .translate("Failed to get column name " + i + " from ResultSetMetaData", "UNKNOWN", sqle);
        }

        res.setAttribute(SqlAttributes.COLUMN_NAME, columnName);
        super.performSubtasks(req, res);
    }
}

From source file:com.aw.core.dao.AWQueryExecuter.java

private String[] buildColumnNames(ResultSet rs, BeanWrapper wrapper) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    List<String> colNames = new ArrayList<String>(meta.getColumnCount());

    for (int i = 0; i < meta.getColumnCount(); i++) {
        String colName = meta.getColumnName(i + 1);
        if (wrapper != null && wrapper.isWritableProperty(colName))
            colNames.add(colName);/*from w  w  w . j  av a 2 s  . com*/
    }
    return colNames.toArray(new String[colNames.size()]);
}