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.novartis.opensource.yada.format.ResultSetResultXMLConverter.java

/**
 * Constructs an xml fragment of {@code ROW} elements with the result set data
 * @param rs the result set containing the data to be converted
 * @return a {@link DocumentFragment} containing the result data wrapped in XML
 * @throws SQLException when {@code rs} cannot be iterated or accessed
 *//*from   ww w  .  j a v  a 2  s . c o m*/
private DocumentFragment getXMLRows(ResultSet rs) throws SQLException {
    DocumentFragment rows = this.doc.createDocumentFragment();

    ResultSetMetaData rsmd = rs.getMetaData();
    if (rsmd == null)
        rsmd = new RowSetMetaDataImpl();
    while (rs.next()) {
        Element row = this.doc.createElement(ROW);
        String colValue;
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String colName = rsmd.getColumnName(i);
            if (!colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
                String col = isHarmonized() && ((JSONObject) this.harmonyMap).has(colName)
                        ? ((JSONObject) this.harmonyMap).getString(colName)
                        : colName;
                if (null == rs.getString(colName) || NULL.equals(rs.getString(colName))) {
                    colValue = NULL_REPLACEMENT;
                } else {
                    colValue = rs.getString(colName);
                }
                Element column = this.doc.createElement(col);
                Text value = this.doc.createTextNode(colValue);
                column.appendChild(value);
                row.appendChild(column);
            }
        }
        rows.appendChild(row);
    }
    return rows;

}

From source file:com.novartis.opensource.yada.format.ResultSetResultDelimitedConverter.java

/**
 * Converts columns of data in a {@link java.sql.ResultSet} to collection
 * of {@link List} objects containing values and stored in the current
 * {@link YADAQueryResult#getConvertedResults()} structure.
 * // w  w w . ja v a2s .  co m
 * @param rs
 *          the result set to convert
 * @throws SQLException
 *           when {@link ResultSet} or {@link ResultSetMetaData} iteration
 *           fails
 */
protected void getDelimitedRows(ResultSet rs) throws SQLException {
    JSONObject h = (JSONObject) this.harmonyMap;
    ResultSetMetaData rsmd = rs.getMetaData();
    if (rsmd == null) // TODO What happens to headers when rsmd is null, or
                      // resultSet is empty?
        rsmd = new RowSetMetaDataImpl();
    int colCount = rsmd.getColumnCount();
    boolean hasYadaRnum = rsmd.getColumnName(colCount).toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS);

    // handle headers
    // TODO How to suppress headers?
    for (int j = 1; j <= colCount; j++) {
        String colName = rsmd.getColumnName(j);
        if (!hasYadaRnum || !colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
            String col = colName;
            if (isHarmonized()) {
                if (h.has(colName)) {
                    col = h.getString(colName);
                }
            }
            getYADAQueryResult().addConvertedHeader(this.wrap(col));
        }
    }
    List<List<String>> convertedResult = new ArrayList<>();
    while (rs.next()) {
        List<String> resultsRow = new ArrayList<>();
        String colValue;
        for (int j = 1; j <= colCount; j++) {
            String colName = rsmd.getColumnName(j);
            if (!hasYadaRnum || !colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
                if (null == rs.getString(colName) || "null".equals(rs.getString(colName))) {
                    colValue = NULL_REPLACEMENT;
                } else {
                    colValue = this.wrap(rs.getString(colName));
                }
                resultsRow.add(colValue);
            }
        }
        convertedResult.add(resultsRow);
    }
    getYADAQueryResult().getConvertedResults().add(convertedResult);
}

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

public List<String> getColumns(Connection connection, String tableName) {

    List<String> columns = new ArrayList<>();

    try {// w  w w. ja v a2  s .  co  m
        ResultSetMetaData rsmd = getDatabaseMetaData(connection, tableName);

        int columnCount = rsmd.getColumnCount();

        IntStream.range(1, columnCount + 1).forEach(i -> {
            try {
                columns.add(rsmd.getColumnName(i));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return columns;
}

From source file:cz.lbenda.dataman.db.sql.SQLSExecutor.java

private void statementToSQLQueryResult(SQLQueryResult result, Tuple2<PreparedStatement, SQLException> tuple) {
    if (tuple.get2() != null) {
        result.setErrorMsg(tuple.get2().getMessage());
        LOG.debug(String.format("Problem with execute SQL '%s'", result.getSql()), tuple.get2());
        if (consoleShower != null) {
            consoleShower.accept(this);
        }//from w  ww.j  a  v a 2s  .c  om
    } else {
        try {
            boolean ex = tuple.get1().execute();
            if (ex) {
                try (ResultSet rs = tuple.get1().getResultSet()) {
                    ResultSetMetaData mtd = rs.getMetaData();
                    SQLQueryRows sqlRows = new SQLQueryRows();
                    sqlRows.setSQL(result.getSql());
                    result.setSqlQueryRows(sqlRows);
                    int columnCount = mtd.getColumnCount();
                    ColumnDesc columns[] = new ColumnDesc[columnCount];
                    for (int i = 1; i <= columnCount; i++) {
                        columns[i - 1] = new ColumnDesc(mtd, i, dbConfig.getDialect());
                    }
                    sqlRows.getMetaData().setColumns(columns);
                    while (rs.next()) {
                        RowDesc row = RowDesc.createNewRow(sqlRows.getMetaData(), RowDesc.RowDescState.LOADED);
                        for (ColumnDesc columnDesc : sqlRows.getMetaData().getColumns()) {
                            row.loadInitialColumnValue(columnDesc, rs);
                        }
                        sqlRows.getRows().add(row);
                    }
                }
            } else {
                result.setAffectedRow(tuple.get1().getUpdateCount());
            }
        } catch (SQLException e) {
            result.setErrorMsg(e.getMessage());
            LOG.debug(String.format("Problem with execute SQL '%s'", result.getSql()), e);
        }
    }
}

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

public List<DataSourceColumn> findColumns(Connection connection, String tableName) {

    List<DataSourceColumn> columns = new ArrayList<>();

    try {/* w w  w.j  a va 2 s .c om*/
        ResultSetMetaData rsmd = getDatabaseMetaData(connection, tableName);

        int columnCount = rsmd.getColumnCount();

        IntStream.range(1, columnCount + 1).forEach(i -> {
            try {
                columns.add(prepareDataSourceColumns(rsmd, i));
            } catch (SQLException e) {
                throw new PlatformRuntimeException(e);
            }
        });

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

    return columns;
}

From source file:com.zimbra.cs.db.JdbcClient.java

private void runSql(Connection conn, String sql) {
    Matcher m = PAT_SELECT.matcher(sql);

    if (m.find()) {
        // Run query and display results 
        try {//  w ww .  j a  va  2s.c  o m
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            int colCount = md.getColumnCount();
            List<Object[]> firstRows = new ArrayList<Object[]>();
            int rowCount = 0;

            // Set initial column widths based on column labels
            int[] colWidths = new int[colCount];
            if (mShowColumnNames) {
                for (int i = 0; i < colCount; i++) {
                    String name = md.getColumnLabel(i + 1);
                    if (name.length() > colWidths[i]) {
                        colWidths[i] = name.length();
                    }
                }
            }

            // Read first 1000 rows first to calculate column widths for printing
            while (rowCount < 1000 && rs.next()) {
                Object[] row = getCurrentRow(rs);
                for (int i = 0; i < colCount; i++) {
                    Object o = row[i];
                    int width = (o == null) ? NULL.length() : (o.toString()).length();
                    if (width > colWidths[i]) {
                        colWidths[i] = width;
                    }
                }
                firstRows.add(row);
                rowCount++;
            }

            // Print first rows
            if (!mBatch && mShowColumnNames) {
                // Skip if we're in batch mode.  If not displaying column names, don't
                // print the first divider.
                printDivider(colWidths);
            }
            if (mShowColumnNames) {
                String[] colNames = new String[colCount];
                for (int i = 0; i < colCount; i++) {
                    colNames[i] = md.getColumnLabel(i + 1);
                }
                printRow(colNames, colWidths);
            }
            if (!mBatch) {
                printDivider(colWidths);
            }
            for (Object[] row : firstRows) {
                printRow(row, colWidths);
            }

            // Print any remaining rows
            while (rs.next()) {
                Object[] row = getCurrentRow(rs);
                printRow(row, colWidths);
            }
            if (!mBatch) {
                printDivider(colWidths);
            }
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    } else {
        // Run statement
        try {
            Statement stmt = conn.createStatement();
            int numRows = stmt.executeUpdate(sql);
            stmt.close();
            System.out.println("Updated " + numRows + " rows");
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from  w w  w  .  j a v  a2  s . com*/
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    for (int index = 1; index <= columnCount; index++) {
        String column = lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    return mappedObject;
}

From source file:SeeAccount.java

public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse)
        throws ServletException, IOException {

    PrintWriter out = null;//from  w w  w.  jav  a2  s . co m
    Connection connection = null;
    Statement statement = null;

    ResultSet rs;

    try {
        outResponse.setContentType("text/html");
        out = outResponse.getWriter();

        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        statement = connection.createStatement();
        rs = statement.executeQuery("SELECT * FROM acc_acc");
        ResultSetMetaData md = rs.getMetaData();

        out.println("<HTML><HEAD><TITLE>        Thumbnail Identification Record</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("Account Information:<BR>");
        out.println("<table>");
        out.println("<tr><td>");
        for (int i = 1; i <= md.getColumnCount(); i++) {
            out.println("Column #" + i + "<BR>");
            out.println("getColumnName : " + md.getColumnName(i) + "<BR>");
            out.println("getColumnClassName : " + md.getColumnClassName(i) + "<BR>");
            out.println("getColumnDisplaySize : " + md.getColumnDisplaySize(i) + "<BR>");
            out.println("getColumnType : " + md.getColumnType(i) + "<BR>");
            out.println("getTableName : " + md.getTableName(i) + "<BR>");
            out.println("<HR>");
        }
        out.println("</BODY></HTML>");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from   w w w.  ja  v a2 s  .c o  m*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(column.replaceAll(" ", ""));
        PropertyDescriptor pd = this.mappedFields.get(field);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (rowNumber == 0 && logger.isDebugEnabled()) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type ["
                            + ClassUtils.getQualifiedName(pd.getPropertyType()) + "]");
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException ex) {
                    if (value == null && this.primitivesDefaultedForNullValue) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Intercepted TypeMismatchException for row " + rowNumber
                                    + " and column '" + column + "' with null value when setting property '"
                                    + pd.getName() + "' of type ["
                                    + ClassUtils.getQualifiedName(pd.getPropertyType()) + "] on object: "
                                    + mappedObject, ex);
                        }
                    } else {
                        throw ex;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex);
            }
        } else {
            // No PropertyDescriptor found
            if (rowNumber == 0 && logger.isDebugEnabled()) {
                logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'");
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException(
                "Given ResultSet does not contain all fields " + "necessary to populate object of class ["
                        + this.mappedClass.getName() + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlSql.java

public String checkSqlSelect()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    JDBCConnection jdbcCnx = getNewJdbcConnection();
    Transaction transaction = null;//from   www. j a  v a 2  s.c o  m
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        transaction = getNewTransaction(jdbcCnx);
        Query query = transaction.prepare(sqlSelect);
        query.getStatement().setFetchSize(getBufferSize());
        ResultSet resultSet = query.getResultSet();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        pw.print("Found ");
        pw.print(columnCount);
        pw.println(" column(s)");
        for (int i = 1; i <= columnCount; i++) {
            pw.print(i);
            pw.print(": ");
            pw.println(metaData.getColumnLabel(i));
        }
        return sw.toString();
    } finally {
        IOUtils.close(pw, sw);
        if (transaction != null)
            transaction.close();
    }
}