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:fr.bird.bloom.model.DatabaseTreatment.java

/**
 * Format request result// w ww  .  j av  a 2s  .c o  m
 * 
 * @param resultMeta
 * @throws SQLException
 * @return void
 */
public void setResultatSelect(ResultSetMetaData resultMeta) throws SQLException {
    resultatSelect = new ArrayList<>();

    String firstLine = "";
    for (int i = 1; i <= resultMeta.getColumnCount(); i++) {
        firstLine += resultMeta.getColumnName(i) + ",";
    }
    firstLine = firstLine.substring(0, firstLine.length() - 1);
    resultatSelect.add(firstLine);

    while (resultSet.next()) {
        String line = "";
        for (int i = 1; i <= resultMeta.getColumnCount(); i++) {

            try {
                //System.out.print(resultSet.getObject(i) + "\t");
                line += "\"" + resultSet.getObject(i) + "\"" + ",";
            } catch (Exception e) {
                line += "\"\",";
            }

        }
        line = line.substring(0, line.length() - 1);
        //System.out.println(line);
        resultatSelect.add(line);
    }
}

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

@Override
public DataHeader fetchAll2(File snapshotDirectory, Timestamp modifiedAfter, String objectName,
        final String keyName, final String updateTimeColumnName) {
    File objectFile = new File(snapshotDirectory, "data-" + objectName + ".dat");
    final GenericConsumer genericConsumer = new SequenceFileConsumer(objectFile);
    final DataHeader dataHeader = new DataHeader();

    String sql = "SELECT * FROM " + objectName + " o where o.update_time >= ?";

    getJdbcTemplate().query(sql, new Object[] { modifiedAfter }, new RowCallbackHandler() {

        @Override//from  w w  w .ja  va2s. co  m
        public void processRow(ResultSet row) throws SQLException {
            final Map<String, Object> dataMap = new HashMap<String, Object>();
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                dataMap.put(rsm.getColumnName(column), row.getObject(rsm.getColumnLabel(column)));
            }

            DataRecord dataRecord = new GenericDataRecord(dataMap, keyName, globalMvdbKeyMaker,
                    updateTimeColumnName, new GlobalMvdbUpdateTimeMaker());
            genericConsumer.consume(dataRecord);
            dataHeader.incrementCount();

        }
    });

    genericConsumer.flushAndClose();

    writeDataHeader(dataHeader, objectName, snapshotDirectory);
    return dataHeader;
}

From source file:com.slemarchand.sqlqueryscripting.scripting.sqlquery.SQLQueryExecutor.java

private List<List<Object>> _execQuery(String sqlQuery, int maxRows, List<String> columnLabels)
        throws SQLException {

    List<List<Object>> rows = null;

    Connection con = null;/*from  w ww.j  av a  2 s . com*/
    Statement stmt = null;
    ResultSet rs = null;

    try {
        con = DataAccess.getConnection();

        con.setAutoCommit(false); // Prevent data updates

        stmt = con.createStatement();
        stmt.setMaxRows(maxRows);
        rs = stmt.executeQuery(sqlQuery);

        ResultSetMetaData md = rs.getMetaData();
        int cc = md.getColumnCount();

        rows = new ArrayList<List<Object>>(cc);

        columnLabels.clear();

        for (int c = 1; c <= cc; c++) {
            String cl = md.getColumnLabel(c);
            columnLabels.add(cl);
        }

        while (rs.next()) {
            List<Object> row = new ArrayList<Object>(cc);
            for (int c = 1; c <= cc; c++) {
                Object value = rs.getObject(c);
                row.add(value);
            }
            rows.add(row);
        }

    } finally {
        DataAccess.cleanUp(con, stmt, rs);
    }

    return rows;
}

From source file:kenh.xscript.database.beans.ResultSetBean.java

/**
 * Use result set to initial a bean.// w w  w  . j av a 2 s. co  m
 * 
 * @param rs
 * @param includeFieldName
 * @throws SQLException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public ResultSetBean(ResultSet rs, boolean includeFieldName)
        throws SQLException, IllegalAccessException, InstantiationException {
    include_field_name = includeFieldName;

    LazyDynaClass beanClass = new LazyDynaClass();

    ResultSetMetaData m = rs.getMetaData();
    for (int i = 1; i <= m.getColumnCount(); i++) {
        Column c = new Column();

        try {
            c.catalogName = m.getCatalogName(i);
        } catch (SQLException e) {
        }
        try {
            c.className = m.getColumnClassName(i);
        } catch (SQLException e) {
        }
        try {
            c.displaySize = m.getColumnDisplaySize(i);
        } catch (SQLException e) {
        }
        try {
            c.label = m.getColumnLabel(i);
        } catch (SQLException e) {
        }
        try {
            c.name = m.getColumnName(i);
        } catch (SQLException e) {
        }
        try {
            c.type = m.getColumnType(i);
        } catch (SQLException e) {
        }
        try {
            c.typeName = m.getColumnTypeName(i);
        } catch (SQLException e) {
        }
        try {
            c.precision = m.getPrecision(i);
        } catch (SQLException e) {
        }
        try {
            c.scale = m.getScale(i);
        } catch (SQLException e) {
        }
        try {
            c.schemaName = m.getSchemaName(i);
        } catch (SQLException e) {
        }
        try {
            c.tableName = m.getTableName(i);
        } catch (SQLException e) {
        }

        beanClass.add(m.getColumnLabel(i).toLowerCase());
        beanClass.add("" + i);

        cols.add(c);
    }

    DynaBean colBean = beanClass.newInstance();
    int i = 1;
    for (Column col : cols) {
        String field = col.getLabel().toLowerCase();
        colBean.set(field, col.getLabel());
        colBean.set("" + i, col.getLabel());
        i++;
    }

    if (include_field_name)
        rows.add(colBean);

    while (rs.next()) {
        DynaBean bean = beanClass.newInstance();
        i = 1;
        for (Column c : cols) {
            String field = c.getLabel().toLowerCase();
            Object obj = rs.getObject(field);
            bean.set(field, obj);
            bean.set("" + i, obj);
            i++;
        }
        rows.add(bean);
    }

}

From source file:ViewDB.java

 /**
 * Constructs the data panel./*from   w ww  . j  a v  a 2  s . com*/
 * @param rs the result set whose contents this panel displays
 */
public DataPanel(RowSet rs) throws SQLException
{
   fields = new ArrayList<JTextField>();
   setLayout(new GridBagLayout());
   GridBagConstraints gbc = new GridBagConstraints();
   gbc.gridwidth = 1;
   gbc.gridheight = 1;

   ResultSetMetaData rsmd = rs.getMetaData();
   for (int i = 1; i <= rsmd.getColumnCount(); i++)
   {
      gbc.gridy = i - 1;

      String columnName = rsmd.getColumnLabel(i);
      gbc.gridx = 0;
      gbc.anchor = GridBagConstraints.EAST;
      add(new JLabel(columnName), gbc);

      int columnWidth = rsmd.getColumnDisplaySize(i);
      JTextField tb = new JTextField(columnWidth);
      if (!rsmd.getColumnClassName(i).equals("java.lang.String"))
         tb.setEditable(false);
               
      fields.add(tb);

      gbc.gridx = 1;
      gbc.anchor = GridBagConstraints.WEST;
      add(tb, gbc);
   }
}

From source file:com.kumarvv.setl.core.Extractor.java

/**
 * parses data row to {@link Row} object
 *
 * @param jrs/* w  w w  .  j  a v a  2s  .co m*/
 * @param meta
 * @return {@link Row}
 * @throws SQLException
 */
Row parseDataRow(JdbcRowSet jrs, ResultSetMetaData meta) throws SQLException {
    if (jrs == null || meta == null) {
        return null;
    }

    int colCount = meta.getColumnCount();

    Map<String, Object> row = new HashMap<>();
    for (int c = 1; c <= colCount; c++) {
        row.put(meta.getColumnName(c).toLowerCase(), jrs.getObject(c));
    }

    Row ro = new Row(fromColumns, row);
    addToQueue(ro);
    return ro;
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

private TableModel retrieveDatasetForQuery(String directory, String query, ObjectId head)
        throws CitationDBException {

    try (Connection conn = getCSVConnection(directory)) {
        Statement stmt = conn.createStatement();
        ResultSet set = stmt.executeQuery(query);
        ResultSetMetaData metaData = set.getMetaData();
        int columnCount = metaData.getColumnCount();

        String[] columns = new String[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columns[i - 1] = metaData.getColumnName(i);
        }/*from   ww  w.ja  v  a2s . c  o m*/

        TableModelMetaData tableMetaData = new DefaultTableModelMetaData(new DefaultRevision(head.getName()));
        DefaultTableModel model = new DefaultTableModel(tableMetaData, Arrays.asList(columns));

        while (set.next()) {
            String[] row = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                row[i - 1] = (String) set.getObject(i);

            }
            model.addRow(row);
        }

        return model;
    } catch (SQLException e) {
        throw new CitationDBException(e);
    }
}

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

private List<ResultRow> convertNativeResults(ResultSet mrs) throws Throwable {
    ResultSetMetaData rsmd = mrs.getMetaData();
    ArrayList<ResultRow> converted = new ArrayList<ResultRow>();
    while (mrs.next()) {
        ResultRow rr = new ResultRow();
        for (int i = 0; i < rsmd.getColumnCount(); i++) {
            rr.addResultColumn(mrs.getObject(i + 1), mrs.wasNull());
        }/*  w  w w  . j  a  v a  2s.  c  o m*/
        converted.add(rr);
    }
    return converted;
}

From source file:be.bittich.dynaorm.repository.GenericDynaRepository.java

/**
 * Configuration//from  w  w w  . ja v a2  s .  c o m
 */
private void configure() {
    runner = getQueryRunner();
    dialect = getDialect();
    // default tableName
    TableFromDB table = AnnotationProcessor.getAnnotationType(clazz, TableFromDB.class);
    String tableName = clazz.getSimpleName().toLowerCase();
    if (table != null && !isEmpty(table.tableName())) {
        tableName = table.tableName();
    }
    tableColumn = new TableColumn(tableName);
    rowProcessor = new DynaRowProcessor(tableColumn);
    try {
        ResultSet rs = runner.getDataSource().getConnection()
                .prepareStatement(dialect.requestForTableColumns(tableName)).executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        Integer nbColumns = metaData.getColumnCount();
        for (int i = 1; i <= nbColumns; i++) {
            String name = metaData.getColumnName(i);
            int type = metaData.getColumnType(i);
            tableColumn.addColumn(name, type);
        }
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:com.adaptris.core.services.jdbc.JdbcDataCaptureServiceImpl.java

protected void saveKeys(AdaptrisMessage msg, Statement stmt) throws SQLException {
    ResultSet rs = null;//  ww  w. j  av a2 s  .co m
    Statement savedKeysQuery = null;

    try {
        if (saveReturnedKeys()) {
            if (!actor.isOldJbc()) {
                rs = stmt.getGeneratedKeys();
                rs.next();
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String name = rsmd.getColumnName(i);
                    String value = rs.getObject(name).toString();
                    msg.addMetadata(name, value);
                }
            } else {
                savedKeysQuery = createStatement(actor.getSqlConnection());
                rs = savedKeysQuery.executeQuery(
                        "select max(" + saveReturnedKeysColumn + ") from " + saveReturnedKeysTable + ";");
                rs.next();
                String value = rs.getObject(saveReturnedKeysColumn).toString();
                msg.addMetadata(saveReturnedKeysColumn, value);
            }
        }
    } finally {
        JdbcUtil.closeQuietly(savedKeysQuery);
        JdbcUtil.closeQuietly(rs);
    }
}