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:DatabaseBrowser.java

public ResultSetTableModel(ResultSet rset) throws SQLException {
    Vector rowData;/* w w w  . java  2  s. c  om*/
    ResultSetMetaData rsmd = rset.getMetaData();
    int count = rsmd.getColumnCount();
    columnHeaders = new Vector(count);
    tableData = new Vector();
    for (int i = 1; i <= count; i++) {
        columnHeaders.addElement(rsmd.getColumnName(i));
    }
    while (rset.next()) {
        rowData = new Vector(count);
        for (int i = 1; i <= count; i++) {
            rowData.addElement(rset.getObject(i));
        }
        tableData.addElement(rowData);
    }
}

From source file:db.migration.V055__UpdateECTS.java

private int getNextHibernateSequence(JdbcTemplate jdbcTemplate) {
    // Returns next global id
    List<Map> resultSet = jdbcTemplate.query("SELECT nextval('public.hibernate_sequence')",
            new RowMapper<Map>() {
                @Override/*from   w  w  w  . j a v a 2  s .  c o m*/
                public Map mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Map r = new HashMap<String, Object>();

                    ResultSetMetaData metadata = rs.getMetaData();
                    for (int i = 1; i <= metadata.getColumnCount(); i++) {
                        String cname = metadata.getColumnName(i);
                        int ctype = metadata.getColumnType(i);

                        switch (ctype) {
                        case Types.BIGINT: // id
                            r.put(cname, rs.getInt(cname));
                            break;

                        default:
                            break;
                        }
                    }

                    return r;
                }
            });

    for (Map m : resultSet) {
        return (int) m.get("nextval");
    }
    return 0;
}

From source file:user.Query.java

public CategoryDataset getWeatherAndTweets() {
    query = " SELECT (Select COUNT(*)" + " FROM TWEET, WEATHER" + " WHERE WEATHER.RAIN = 'false' "
            + " AND WEATHER.SNOW = 'false' " + " AND TWEET.DATE = WEATHER.DATE ) as \"Amount good weather\""
            + " ," + " (SELECT COUNT(*) " + " FROM TWEET, WEATHER" + " WHERE WEATHER.RAIN =  'true'"
            + " AND TWEET.DATE = WEATHER.DATE ) as \"Amount bad weather\"" + "  FROM tweet, weather"
            + " Where tweet." + time.substring(1) + " Group by \"Amount good weather\"; ";

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    try {/* w w  w.j  av a  2  s .c  o m*/
        ResultSet resultSet = executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();
        while (resultSet.next()) {
            int count = metaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                dataset.addValue(Integer.parseInt(resultSet.getString(i)), "Tweets", metaData.getColumnName(i));
            }
        }
    } catch (SQLException ex) {
    }
    return dataset;
}

From source file:user.Query.java

public DefaultPieDataset getBlijdorpTweets() {
    query = "   SELECT " + "    (" + " SELECT count(*) " + " FROM Tweet " + " WHERE AREA != ' no area' "
            + " AND ANIMAL = ' no animal' " + " AND User_name = ' Diergaarde Blijdorp'" + " AND " + time
            + " ) AS Tweets_About_Areas, (" + " SELECT count(*) " + " FROM Tweet "
            + " WHERE  ANIMAL != ' no animal' " + " AND User_name = ' Diergaarde Blijdorp' " + " AND " + time
            + " ) AS Tweets_About_Animals," + " (" + " SELECT count(*) " + " FROM Tweet "
            + " WHERE  ANIMAL = ' no animal' " + " AND  AREA = ' no area' "
            + " AND User_name = ' Diergaarde Blijdorp' " + "  AND " + time + " ) AS 'Other_Tweets'" + " ;";
    DefaultPieDataset dataset = new DefaultPieDataset();
    try {/*from   w  w w . j av  a  2  s . c om*/
        ResultSet resultSet = executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();
        while (resultSet.next()) {
            int count = metaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                dataset.setValue(metaData.getColumnName(i), Integer.parseInt(resultSet.getString(i)));
            }
        }
    } catch (SQLException ex) {
    }
    return dataset;
}

From source file:com.graphaware.importer.data.access.QueueDbDataReader.java

/**
 * {@inheritDoc}/*from www. j  a  va2  s  .  co m*/
 */
@Override
public final void read(final String query, final String hint) {
    if (records != null) {
        throw new IllegalStateException("Previous reader hasn't been closed");
    }

    LOG.info("Start query: \n" + query);

    if (query.startsWith("alter")) {
        jdbcTemplate.execute(query);
        noMoreRecords = true;
        return;
    }

    records = new ArrayBlockingQueue<>(queueCapacity());

    new Thread(new Runnable() {
        @Override
        public void run() {
            Date d1 = Calendar.getInstance().getTime();

            try {
                jdbcTemplate.query(query, new ResultSetExtractor<Void>() {
                    @Override
                    public Void extractData(ResultSet rs) throws SQLException, DataAccessException {
                        ResultSetMetaData metaData = rs.getMetaData();
                        int colCount = metaData.getColumnCount();

                        while (rs.next()) {
                            Map<String, String> columns = new HashMap<>();
                            for (int i = 1; i <= colCount; i++) {
                                columns.put(metaData.getColumnLabel(i), rs.getString(i));
                            }
                            columns.put(ROW, String.valueOf(rs.getRow()));

                            try {
                                records.offer(columns, 1, TimeUnit.HOURS);
                            } catch (InterruptedException e) {
                                LOG.warn(
                                        "Was waiting for more than 1 hour to insert a record for processing, had to drop it");
                            }
                        }

                        return null;
                    }
                });
            } finally {
                noMoreRecords = true;
            }

            long diffInSeconds = TimeUnit.MILLISECONDS
                    .toSeconds(Calendar.getInstance().getTime().getTime() - d1.getTime());

            LOG.info("Finished querying for " + hint + " in " + diffInSeconds + " seconds");
        }
    }, "DB READER - " + hint).start();
}

From source file:com.github.tosdan.utils.sql.BasicRowProcessorMod.java

/**
 * Convert a <code>ResultSet</code> row into an <code>Object[]</code>.
 * This implementation copies column values into the array in the same
 * order they're returned from the <code>ResultSet</code>.  Array elements
 * will be set to <code>null</code> if the column was SQL NULL.
 *
 * @see org.apache.commons.dbutils.RowProcessor#toArray(java.sql.ResultSet)
 * @param rs ResultSet that supplies the array data
 * @throws SQLException if a database access error occurs
 * @return the newly created array//from  ww w .j  a va2s .c o  m
 */
@Override
public Object[] toArray(ResultSet rs) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    int cols = meta.getColumnCount();
    Object[] result = new Object[cols];

    for (int i = 0; i < cols; i++) {
        result[i] = rs.getObject(i + 1);
    }

    return result;
}

From source file:com.github.tosdan.utils.sql.BasicRowProcessorMod.java

/**
 * Convert a <code>ResultSet</code> row into a <code>Map</code>.  This
 * implementation returns a <code>Map</code> with case insensitive column
 * names as keys.  Calls to <code>map.get("COL")</code> and
 * <code>map.get("col")</code> return the same value.
 * @see org.apache.commons.dbutils.RowProcessor#toMap(java.sql.ResultSet)
 * @param rs ResultSet that supplies the map data
 * @throws SQLException if a database access error occurs
 * @return the newly created Map//from   w  w  w. j  a v  a2s . c  o m
 */
@Override
public Map<String, Object> toMap(ResultSet rs) throws SQLException {
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();

    for (int i = 1; i <= cols; i++) {
        Object obj = rs.getObject(i);
        result.put(rsmd.getColumnName(i), obj);
    }

    return result;
}

From source file:com.handu.open.dubbo.monitor.dao.base.DubboInvokeBaseDAO.java

/**
 * SQL?//from  ww w. j  ava 2 s  . c  o m
 *
 * @param sql SQL?
 * @return List<Map>
 */
public List<Map> querySql(String sql) {
    List<Map> list = Lists.newArrayList();
    try {
        ResultSet rs = getSqlSession().getConnection()
                .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)
                .executeQuery();
        try {
            ResultSetMetaData rsm = rs.getMetaData(); //
            int col = rsm.getColumnCount(); //
            String[] colName = new String[col];
            //???, colName
            for (int i = 0; i < col; i++) {
                colName[i] = rsm.getColumnName(i + 1);
            }
            rs.beforeFirst();
            while (rs.next()) {
                Map<String, String> map = Maps.newHashMap();
                for (String aColName : colName) {
                    map.put(aColName, rs.getString(aColName));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:com.netspective.sparx.form.DialogContextUtils.java

public void populateFieldValuesFromResultSet(DialogContext dc, ResultSet rs) throws SQLException {
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        DialogFieldStates fieldStates = dc.getFieldStates();
        for (int i = 1; i <= colsCount; i++) {
            String fieldName = rsmd.getColumnName(i).toLowerCase();
            DialogField.State state = fieldStates.getState(fieldName, null);
            if (state != null) {
                // for columns that are Date objects, use the object setter instead of the text setter
                // because we don't need to do unnecessary formatting/parsing
                if (rsmd.getColumnType(i) == Types.DATE)
                    state.getValue().setValue(rs.getDate(i));
                else
                    state.getValue().setTextValue(rs.getString(i));
            }// w  w  w.  jav a  2s. co  m
        }
    }
}

From source file:com.mvdb.etl.dao.impl.JdbcOrderDAO.java

@Override
public Map<String, ColumnMetadata> findMetadata() {
    String sql = "SELECT * FROM ORDERS limit 1";
    final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>();

    getJdbcTemplate().query(sql, new RowCallbackHandler() {

        @Override//from   w  w w  . j av a 2s  .c  o m
        public void processRow(ResultSet row) throws SQLException {
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                ColumnMetadata metadata = new ColumnMetadata();
                metadata.setColumnLabel(rsm.getColumnLabel(column));
                metadata.setColumnName(rsm.getColumnName(column));
                metadata.setColumnType(rsm.getColumnType(column));
                metadata.setColumnTypeName(rsm.getColumnTypeName(column));

                metaDataMap.put(rsm.getColumnName(column), metadata);
            }

        }
    });

    return metaDataMap;
}