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.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 www .j  a  va 2  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:com.p5solutions.core.jpa.orm.rowbinder.EntityRowBinder.java

protected int findColumnIndex(ResultSetMetaData metaData, String columnName) throws SQLException {
    // TODO fix this or cache it somehow, so it doesn't iterate each query
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        String name = metaData.getColumnName(i);

        if (name.toUpperCase().equals(columnName)) {
            return i;
        }// w ww  . j a  v a 2s  .co m
    }
    return -1;
}

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  ww  w . j  a  v  a2s .c om
        colNames[i] = adaptName(cName);
        FieldFormatter fF = fieldNameToFormatter.get(cName);
        if (fF == null) {
            fF = fieldIdToFormatter.get("" + i);
        }
        fFormatters[i] = fF;
    }
}

From source file:com.gmail.sretof.db.jdbc.processor.CamelBeanProcessor.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>.
 * /*ww  w  .  j  a va 2s. c  om*/
 * @param rsmd
 *            The <code>ResultSetMetaData</code> containing column
 *            information.
 * 
 * @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);
        }
        columnName = columnName.toLowerCase();
        String propertyName = columnToPropertyOverrides.get(columnName);
        if (propertyName == null) {
            propertyName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);// ?
        }
        for (int i = 0; i < props.length; i++) {
            String prop = props[i].getName();
            if (propertyName.equalsIgnoreCase(prop)) {
                columnToProperty[col] = i;
                break;
            }
        }
    }
    return columnToProperty;
}

From source file:com.netspective.axiom.value.source.QueryResultsValueSource.java

public Value getQueryResults(ValueContext vc, int style) {
    ValueSources.getInstance().assertValueContextInstance(DatabaseConnValueContext.class, vc, this);
    DatabaseConnValueContext dcvc = (DatabaseConnValueContext) vc;

    SqlManager sqlManager = null;//www  .  ja v a2s  . com
    try {
        sqlManager = getSqlManager(dcvc);
        if (sqlManager == null)
            throw new RuntimeException("Unable to locate SQL Manager for " + this);
    } catch (Exception e) {
        log.error("Error retrieving SQL Manager", e);
        throw new NestableRuntimeException(e);
    }

    Query query = sqlManager.getQuery(queryId);
    if (query == null) {
        log.error("Unable to locate Query '" + queryId + "' in SQL Manager '" + sqlManager + "' in " + this
                + ". Available: " + sqlManager.getQueries().getNames());
        if (style == RESULTSTYLE_PRESENTATION) {
            PresentationValue pValue = new PresentationValue();
            PresentationValue.Items items = pValue.createItems();
            items.addItem("Unable to find query " + queryId);
            return pValue;
        } else
            return new GenericValue("Unable to find query " + queryId);
    }

    String dataSourceIdText = dataSourceId != null ? dataSourceId.getTextValue(vc) : null;
    QueryResultSet qrs = null;

    try {
        if (params == null)
            qrs = query.execute(dcvc, dataSourceIdText, null);
        else {
            Object[] parameters = new Object[params.length];
            for (int p = 0; p < params.length; p++)
                parameters[p] = params[p].getValue(vc).getValueForSqlBindParam();
            qrs = query.execute(dcvc, dataSourceIdText, parameters);
        }
    } catch (Exception e) {
        log.error("Error executing query", e);
        throw new NestableRuntimeException(e);
    }

    Value value = null;
    try {
        ResultSet rs = qrs.getResultSet();
        switch (style) {
        case RESULTSTYLE_SINGLECOLUMN_OBJECT:
            if (rs.next())
                value = new GenericValue(rs.getObject(1));
            else
                value = null;
            break;

        case RESULTSTYLE_FIRST_ROW_MAP_OBJECT:
            if (rs.next()) {
                Map rowMap = new HashMap();
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++)
                    rowMap.put(rsmd.getColumnName(i), rs.getObject(i));
                value = new GenericValue(rowMap);
            } else
                value = null;
            break;

        case RESULTSTYLE_ALL_ROWS_MAP_LIST:
            List rows = new ArrayList();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                Map rowMap = new HashMap();
                for (int i = 1; i <= rsmd.getColumnCount(); i++)
                    rowMap.put(rsmd.getColumnName(i), rs.getObject(i));
                rows.add(rowMap);
            }
            value = new GenericValue(rows);
            break;

        case RESULTSTYLE_FIRST_ROW_LIST:
            rsmd = rs.getMetaData();
            if (rs.next()) {
                List row = new ArrayList();
                for (int i = 1; i <= rsmd.getColumnCount(); i++)
                    row.add(rs.getObject(i));
                value = new GenericValue(row);
            } else
                value = null;
            break;

        case RESULTSTYLE_ALL_ROWS_LIST:
            rsmd = rs.getMetaData();
            rows = new ArrayList();
            while (rs.next()) {
                List row = new ArrayList();
                for (int i = 1; i <= rsmd.getColumnCount(); i++)
                    row.add(rs.getObject(i));
                rows.add(row);
            }
            value = new GenericValue(rows);
            break;

        case RESULTSTYLE_RESULTSET:
            value = new GenericValue(qrs);
            break;

        case RESULTSTYLE_PRESENTATION:
            PresentationValue pValue = new PresentationValue();
            PresentationValue.Items items = pValue.createItems();
            rsmd = rs.getMetaData();
            rows = new ArrayList();
            switch (rsmd.getColumnCount()) {
            case 1:
                while (rs.next())
                    items.addItem(rs.getString(1));
                break;

            default:
                while (rs.next())
                    items.addItem(rs.getString(1), rs.getString(2));
                break;
            }
            value = pValue;
            break;

        default:
            throw new RuntimeException("Invalid style " + resultStyle + " in " + this);
        }
    } catch (Exception e) {
        log.error("Error retrieving results", e);
        throw new NestableRuntimeException(e);
    } finally {
        if (resultStyle != RESULTSTYLE_RESULTSET) {
            try {
                if (qrs != null)
                    qrs.close(true);
            } catch (SQLException e) {
                log.error("Error closing result set", e);
                throw new NestableRuntimeException(e);
            }
        }
    }
    return value;
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param sql/*  w  ww .j  av a 2  s  . com*/
 * @param project
 * @return
 * @throws Exception
 */
private SQLResponse execute(String sql, SQLRequest sqlRequest) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet resultSet = null;
    List<List<String>> results = new LinkedList<List<String>>();
    List<SelectedColumnMeta> columnMetas = new LinkedList<SelectedColumnMeta>();

    try {
        conn = getOLAPDataSource(sqlRequest.getProject()).getConnection();

        if (sqlRequest instanceof PrepareSqlRequest) {
            PreparedStatement preparedState = conn.prepareStatement(sql);

            for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) {
                setParam(preparedState, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]);
            }

            resultSet = preparedState.executeQuery();
        } else {
            stat = conn.createStatement();
            resultSet = stat.executeQuery(sql);
        }

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // Fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i),
                    metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i),
                    metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i),
                    metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i),
                    metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i),
                    metaData.isWritable(i), metaData.isDefinitelyWritable(i)));
        }

        List<String> oneRow = new LinkedList<String>();

        // fill in results
        while (resultSet.next()) {
            for (int i = 0; i < columnCount; i++) {
                oneRow.add((resultSet.getString(i + 1)));
            }

            results.add(new LinkedList<String>(oneRow));
            oneRow.clear();
        }
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage(), e);
        throw e;
    } finally {
        close(resultSet, stat, conn);
    }

    boolean isPartialResult = false;
    String cube = "";
    long totalScanCount = 0;
    for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) {
        isPartialResult |= ctx.storageContext.isPartialResultReturned();
        cube = ctx.cubeInstance.getName();
        totalScanCount += ctx.storageContext.getTotalScanCount();
    }

    SQLResponse response = new SQLResponse(columnMetas, results, cube, 0, false, null, isPartialResult);
    response.setTotalScanCount(totalScanCount);

    return response;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java

private void validateResultSetMetadata(List<ConfigIssue> issues, Source.Context context, ResultSet rs) {
    Set<String> allTables = new HashSet<>();
    try {//from   ww  w.j a  v  a  2s  .com
        Set<String> columnLabels = new HashSet<>();
        ResultSetMetaData metadata = rs.getMetaData();
        int columnIdx = metadata.getColumnCount() + 1;
        while (--columnIdx > 0) {
            String columnLabel = metadata.getColumnLabel(columnIdx);
            if (columnLabels.contains(columnLabel)) {
                issues.add(
                        context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_31, columnLabel));
            } else {
                columnLabels.add(columnLabel);
            }
            allTables.add(metadata.getTableName(columnIdx));
        }
        if (!StringUtils.isEmpty(offsetColumn) && offsetColumn.contains(".")) {
            issues.add(context.createConfigIssue(Groups.JDBC.name(), OFFSET_COLUMN, JdbcErrors.JDBC_32,
                    offsetColumn));
        } else {
            rs.findColumn(offsetColumn);
        }
    } catch (SQLException e) {
        // Log a warning instead of an error because some implementations such as Oracle have implicit
        // "columns" such as ROWNUM that won't appear as part of the result set.
        LOG.warn(JdbcErrors.JDBC_33.getMessage(), offsetColumn, query);
        LOG.warn(jdbcUtil.formatSqlException(e));
    }
    tableNames = StringUtils.join(allTables, ", ");
}

From source file:com.mapd.utility.SQLImporter.java

private void createMapDTable(ResultSetMetaData metaData) {

    StringBuilder sb = new StringBuilder();
    sb.append("Create table ").append(cmd.getOptionValue("targetTable")).append("(");

    // Now iterate the metadata
    try {// w  ww . j  a v  a  2  s.  co m
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            if (i > 1) {
                sb.append(",");
            }
            LOGGER.debug("Column name is " + metaData.getColumnName(i));
            LOGGER.debug("Column type is " + metaData.getColumnTypeName(i));
            LOGGER.debug("Column type is " + metaData.getColumnType(i));

            sb.append(metaData.getColumnName(i)).append(" ");

            sb.append(getColType(metaData.getColumnType(i), metaData.getPrecision(i), metaData.getScale(i)));
        }
        sb.append(")");

        if (Integer.valueOf(cmd.getOptionValue("fragmentSize", "0")) > 0) {
            sb.append(" with (fragment_size = ");
            sb.append(cmd.getOptionValue("fragmentSize", "0"));
            sb.append(")");
        }

    } catch (SQLException ex) {
        LOGGER.error("Error processing the metadata - " + ex.toString());
        exit(1);
    }

    executeMapDCommand(sb.toString());

}

From source file:com.facebook.presto.accumulo.tools.PaginationTask.java

/**
 * This function executes the query, paging results to stdout
 *
 * @return 0 if successful, non-zero otherwise
 * @throws Exception/*from   www .  j a  va 2 s  . c o  m*/
 */
public int exec() throws Exception {
    try {
        // First, run the query to create the temporary table for pagination
        if (runQuery() == 0) {
            ResultSet rs;
            // Then, begin the pagination
            AlignedTablePrinter table = new AlignedTablePrinter(Arrays.asList(columns),
                    new PrintWriter(System.out));

            // Open up a reader to get user input
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

            // While there are rows to print
            while (this.hasNext()) {
                // Get the next batch of rows
                rs = this.next();

                // Build a list of rows
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnsNumber = rsmd.getColumnCount();
                List<List<?>> rows = new ArrayList<>();
                while (rs.next()) {
                    List<String> row = new ArrayList<>();
                    rows.add(row);
                    for (int i = 1; i <= columnsNumber; i++) {
                        row.add(rs.getString(i));
                    }
                }

                // Print the rows!
                table.printRows(rows, false);

                // If there is still data to present, wait for user input, going to the next
                // page or exiting if 'q' is entered
                if (this.hasNext()) {
                    System.out.println(
                            "--------- Press enter to move onto the next page, or enter 'q' to quit ---------");
                    String line = in.readLine();
                    if (line.equals("q")) {
                        break;
                    }
                }
            }
        }
    } finally {
        // And finally, drop all stuff
        cleanup();
    }

    return 0;
}

From source file:atg.tools.dynunit.test.util.DBUtils.java

void dump(@NotNull ResultSet rs) throws SQLException {

    // the order of the rows in a cursor
    // are implementation dependent unless you use the SQL ORDER statement
    ResultSetMetaData meta = rs.getMetaData();
    int colmax = meta.getColumnCount();
    int i;//from www.  j av  a2 s.  c  o  m
    Object o = null;

    // the result set is a cursor into the data. You can only
    // point to one row at a time
    // assume we are pointing to BEFORE the first row
    // rs.next() points to next row and returns true
    // or false if there is no next row, which breaks the loop
    for (; rs.next();) {
        for (i = 0; i < colmax; ++i) {
            o = rs.getObject(i + 1); // Is SQL the first column is indexed

            // with 1 not 0
            logger.info(o);
        }
    }
}