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.netspective.axiom.sql.ResultSetUtils.java

public String[] getResultSetSingleRowAsStrings(ResultSet rs) throws SQLException {
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        String[] result = new String[colsCount];
        for (int i = 1; i <= colsCount; i++) {
            result[i - 1] = rs.getString(i);
        }//from w ww  .ja  v  a  2 s . c o m
        return result;
    } else
        return null;
}

From source file:com.tesora.dve.sql.util.JdbcConnectionResourceResponse.java

@Override
public List<ColumnChecker> getColumnCheckers() throws Throwable {
    ResultSetMetaData rsmd = results.getMetaData();
    ArrayList<ColumnChecker> checkers = new ArrayList<ColumnChecker>();
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        int dt = rsmd.getColumnType(i);
        if (dt == Types.BINARY || dt == Types.VARBINARY || dt == Types.LONGVARBINARY)
            checkers.add(BLOB_COLUMN);//from w  w w  .  j  a v a 2  s. c  o  m
        else if (dt == Types.TIMESTAMP)
            checkers.add(TIMESTAMP_COLUMN);
        else
            checkers.add(REGULAR_COLUMN);
    }
    return checkers;
}

From source file:RowSetModel.java

public int getColumnCount() {
    try {//  ww w  .  j a va  2 s .c  om
        ResultSetMetaData meta = rowSet.getMetaData();

        if (meta == null) {
            return 0;
        }
        return meta.getColumnCount();
    } catch (SQLException e) {
        return 0;
    }
}

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

public Map getResultSetSingleRowAsMap(ResultSet rs, boolean useLabelAsKey) throws SQLException {
    Map result = new HashMap();
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        for (int i = 1; i <= colsCount; i++) {
            result.put(//from  www.  j a  v  a  2 s .  c om
                    useLabelAsKey ? rsmd.getColumnLabel(i).toLowerCase() : rsmd.getColumnName(i).toLowerCase(),
                    rs.getObject(i));
        }
        return result;
    } else
        return null;
}

From source file:me.doshou.admin.monitor.web.controller.SQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/sql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("sql") String sql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    String lowerCaseSQL = sql.trim().toLowerCase();
    final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update")
            || lowerCaseSQL.startsWith("delete");
    final boolean isDQL = lowerCaseSQL.startsWith("select");

    if (!isDML && !isDQL) {
        model.addAttribute(Constants.ERROR,
                "SQL????insert?update?delete?select");
        return showSQLForm();
    }//from  w w  w.  j av  a2s  .  co  m
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {

                if (isDML) {
                    Query query = em.createNativeQuery(sql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                } else {
                    String findSQL = sql;
                    String countSQL = "select count(*) count from (" + findSQL + ") o";
                    Query countQuery = em.createNativeQuery(countSQL);
                    Query findQuery = em.createNativeQuery(findSQL);
                    findQuery.setFirstResult(pageable.getOffset());
                    findQuery.setMaxResults(pageable.getPageSize());

                    Page page = new PageImpl(findQuery.getResultList(), pageable,
                            ((BigInteger) countQuery.getSingleResult()).longValue());

                    model.addAttribute("resultPage", page);

                    em.unwrap(Session.class).doWork(new Work() {
                        @Override
                        public void execute(final Connection connection) throws SQLException {
                            PreparedStatement psst = connection.prepareStatement(sql);
                            ResultSetMetaData metaData = psst.getMetaData();

                            List<String> columnNames = Lists.newArrayList();
                            for (int i = 1, l = metaData.getColumnCount(); i <= l; i++) {
                                columnNames.add(metaData.getColumnLabel(i));
                            }
                            psst.close();
                            model.addAttribute("columnNames", columnNames);
                        }
                    });
                }

                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showSQLForm();
}

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

public Object[][] getResultSetRowsAsMatrix(ResultSet rs) throws SQLException {
    ArrayList result = new ArrayList();
    while (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        Object[] row = new Object[colsCount];
        for (int i = 1; i <= colsCount; i++) {
            row[i - 1] = rs.getObject(i);
        }/*  w  w w . j a v  a 2  s .  c o  m*/
        result.add(row);
    }

    if (result.size() > 0)
        return (Object[][]) result.toArray(new Object[result.size()][]);
    else
        return null;
}

From source file:com.p5solutions.core.jpa.orm.rowbinder.BasicTypeRowBinder.java

@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
    ResultSetMetaData metaData = rs.getMetaData();

    // / obviously if we have more than one column, we cannot possibly
    // map it//  w  w w .ja  v  a 2s .co  m
    // / to a plain old java object of type Object.class, since there
    // are no
    // / members to map the columns to!
    if (metaData.getColumnCount() > 1) {
        throw new RuntimeException("Cannot return multi-column resultset into "
                + "a plain object of type Object.class. If you need to map a multi-column "
                + "resultset, please use an object marked with @" + Entity.class + " annotation.");
    }

    // // THIS SHOULD NEVER HAPPEN, QUERY EXCEPTION SHOULD
    // // BE THROWN IF THERE IS A SYNTAX ERROR IN THE QUERY.
    // if (metaData.getColumnCount() == 0) { }

    // Otherwise if there is only 1 column, and its within the scope of
    // plain object.class
    // returnResults.add((T)rs.getObject(1));
    return (T) rs.getObject(1);
}

From source file:com.clican.pluto.common.support.spring.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>//from   w w w . j a v  a2s .  co  m
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
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();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.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);
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    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 + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

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

public Map[] getResultSetRowsAsMapArray(ResultSet rs, boolean useLabelAsKey) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colsCount = rsmd.getColumnCount();
    String[] columnNames = new String[colsCount];
    for (int c = 1; c <= colsCount; c++) {
        columnNames[c - 1] = useLabelAsKey ? rsmd.getColumnLabel(c).toLowerCase()
                : rsmd.getColumnName(c).toLowerCase();
    }// www . ja  v a2 s. com

    ArrayList result = new ArrayList();
    while (rs.next()) {
        Map rsMap = new HashMap();
        for (int i = 1; i <= colsCount; i++) {
            rsMap.put(columnNames[i - 1], rs.getObject(i));
        }
        result.add(rsMap);
    }

    if (result.size() > 0)
        return (Map[]) result.toArray(new Map[result.size()]);
    else
        return null;
}

From source file:com.tesora.dve.sql.util.JdbcConnectionResourceResponse.java

private void assertEqualJdbcMetadata(String cntxt, JdbcConnectionResourceResponse other) throws Throwable {
    ResultSetMetaData expected = results.getMetaData();
    ResultSetMetaData actual = other.results.getMetaData();
    assertEquals(cntxt + " result set width", expected.getColumnCount(), actual.getColumnCount());
    int nCols = expected.getColumnCount();
    for (int i = 1; i <= nCols; i++) {
        for (int f = 0; f < mdfields.length; f++) {
            mdfields[f].assertSame(cntxt, i, expected, actual);
        }/*from  ww w.ja v a 2 s . c om*/
    }
}