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:eu.stratosphere.api.java.io.jdbc.JDBCInputFormat.java

private void extractTypes(OUT tuple) throws SQLException, IOException {
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    columnTypes = new int[resultSetMetaData.getColumnCount()];
    if (tuple.getArity() != columnTypes.length) {
        close();//w w  w.j a  va2s  . c o m
        throw new IOException("Tuple size does not match columncount");
    }
    for (int pos = 0; pos < columnTypes.length; pos++) {
        columnTypes[pos] = resultSetMetaData.getColumnType(pos + 1);
    }
}

From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java

@Override
public Map<String, String> queryForMeta(String tableName) {
    long begin = System.currentTimeMillis();
    Map<String, String> result = Maps.newConcurrentMap();
    Connection conn = null;//ww  w.j  ava2  s.  c om
    PreparedStatement pst = null;
    try {
        conn = this.getJdbcTemplate().getDataSource().getConnection();
        DatabaseMetaData dbMetaData = conn.getMetaData();
        if (StringUtils.isNotEmpty(tableName)) {
            pst = conn.prepareStatement(String.format("select * from %s where 1=2", tableName));
            ResultSetMetaData rsd = pst.executeQuery().getMetaData();
            for (int i = 0; i < rsd.getColumnCount(); i++) {
                result.put(rsd.getColumnName(i + 1), rsd.getColumnTypeName(i + 1));
            }
        }
    } catch (SQLException e1) {
        logger.error("queryId:{} select meta error:{}", 1, e1.getCause().getMessage());
    } finally {
        JdbcUtils.closeConnection(conn);
        JdbcUtils.closeStatement(pst);
        logger.info("queryId:{} select meta cost:{} ms resultsize:{}", 1, System.currentTimeMillis() - begin,
                result.size());
    }
    return result;
}

From source file:pl.edu.agh.iosr.lsf.dao.DatabaseHelper.java

public long benchmark(PreparedStatement ps) throws SQLException {
    long start = System.currentTimeMillis();

    try (ResultSet rs = ps.executeQuery()) {

        ResultSetMetaData rsmd = rs.getMetaData();
        int col = rsmd.getColumnCount();

        while (rs.next()) {
            String[] row = new String[col];
            for (int i = 0; i < row.length; ++i) {
                row[i] = rs.getString(i + 1);
            }// w  ww  . jav a2 s  .c om
        }

    } finally {
        ps.close();
    }

    return System.currentTimeMillis() - start;
}

From source file:com.duowan.common.spring.jdbc.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 . ja v  a  2 s . co  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);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        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());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                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:pl.edu.agh.iosr.lsf.dao.DatabaseHelper.java

public List<String[]> select(PreparedStatement ps) throws SQLException {
    List<String[]> result = new LinkedList();

    try (ResultSet rs = ps.executeQuery()) {

        ResultSetMetaData rsmd = rs.getMetaData();
        int col = rsmd.getColumnCount();

        while (rs.next()) {
            String[] row = new String[col];
            for (int i = 0; i < row.length; ++i) {
                row[i] = rs.getString(i + 1);
            }/*from w  w w  .  jav  a 2s.com*/
            result.add(row);
        }

    } finally {
        ps.close();
    }

    return result;
}

From source file:com.insframework.common.spring.jdbc.mapper.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  a 2  s  . c o m
 */
@Override
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);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        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());
                }
                try {
                    //add by guom
                    if (pd.getPropertyType() != null
                            && "java.lang.String".equals(pd.getPropertyType().getName())) {
                        if (value != null) {
                            bw.setPropertyValue(pd.getName(), String.valueOf(value));
                        } else {
                            bw.setPropertyValue(pd.getName(), "");
                        }
                    } else if (pd.getPropertyType() != null
                            && "double".equals(pd.getPropertyType().getName())) {
                        if (value != null) {
                            bw.setPropertyValue(pd.getName(), value);
                        } else {
                            bw.setPropertyValue(pd.getName(), 0d);
                        }
                    } else {
                        bw.setPropertyValue(pd.getName(), value);
                    }

                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.info("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                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:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java

protected List<Map<String, Object>> pull(final String queryString,
        final List<ParameterMapping> parameterMappings, final Object[] args) {

    // log.debug("pulling..." );

    return getJdbcTemplate().query(queryString, args, new RowMapper<Map<String, Object>>() {
        public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Map<String, Object> mapOfColValues = createColumnMap(columnCount);
            for (int i = 1; i <= columnCount; i++) {
                String key = getColumnKey(lookupColumnName(rsmd, i));
                Object obj = getColumnValue(rs, i);
                mapOfColValues.put(key, obj);
            }//from w w  w  .  java2s .c om

            return mapOfColValues;
        }

        protected Map<String, Object> createColumnMap(int columnCount) {
            return new LinkedHashMap<String, Object>(columnCount);
        }

        protected String getColumnKey(String columnName) {
            return columnName;
        }

        protected Object getColumnValue(ResultSet rs, int index) throws SQLException {

            for (ParameterMapping mapping : parameterMappings) {
                // LOG.debug( index + " mapping match :" +
                // mapping.getIndex());
                if (index == mapping.getIndex()) {
                    if (String.class == mapping.getJavaType()) {

                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "";

                        if (!StringUtils.isEmpty(mapping.getCipher())) {
                            try {
                                Cipher cipher = Cipher.getInstance(mapping.getCipher());
                                SecretKeySpec skeySpec = new SecretKeySpec(
                                        Hex.decodeHex(mapping.getCipherKey().toCharArray()),
                                        mapping.getCipherKeyAlg());
                                cipher.init(Cipher.DECRYPT_MODE, skeySpec);

                                byte raw[];
                                if (!StringUtils.isEmpty(mapping.getEncoding())) {
                                    String enc = mapping.getEncoding();
                                    if (enc.toUpperCase().equals("BASE64")) {
                                        raw = Base64.decodeBase64(value);
                                        // BASE64Decoder decoder = new
                                        // BASE64Decoder();
                                        // raw =
                                        // decoder.decodeBuffer(value);
                                    } else {
                                        raw = value.getBytes();
                                    }
                                } else {
                                    raw = value.getBytes();
                                }
                                byte stringBytes[] = cipher.doFinal(raw);
                                return new String(stringBytes);

                            } catch (Exception e) {
                                LOG.error(e);
                            }
                            return value;
                        }

                        if (!StringUtils.isEmpty(mapping.getEncoding())) {
                            String[] encoding = StringUtils.split(mapping.getEncoding(), ">");
                            try {
                                if (encoding.length == 2)
                                    return new String(value.getBytes(encoding[0]), encoding[1]);
                                else if (encoding.length == 1) {
                                    return new String(value.getBytes(), encoding[0]);
                                }
                            } catch (UnsupportedEncodingException e) {
                                LOG.error(e);
                                return value;
                            }
                        }

                    } else if (Long.class == mapping.getJavaType()) {
                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "0";
                        return new Long(value);
                    } else if (Integer.class == mapping.getJavaType()) {
                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "0";
                        return new Integer(value);
                    } else if (Double.class == mapping.getJavaType()) {
                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "0";
                        return new Double(value);
                    }
                }
            }
            return JdbcUtils.getResultSetValue(rs, index);
        }
    });
}

From source file:eu.stratosphere.api.java.record.io.jdbc.JDBCInputFormat.java

/**
 * Stores the next resultSet row in a Record
 * //from   w  ww .  ja  v  a 2  s.  com
 * @param record
 *        target Record
 * @return boolean value indicating that the operation was successful
 */
@Override
public Record nextRecord(Record record) {
    try {
        resultSet.next();
        ResultSetMetaData rsmd = resultSet.getMetaData();
        int column_count = rsmd.getColumnCount();
        record.setNumFields(column_count);

        for (int pos = 0; pos < column_count; pos++) {
            int type = rsmd.getColumnType(pos + 1);
            retrieveTypeAndFillRecord(pos, type, record);
        }
        return record;
    } catch (SQLException e) {
        throw new IllegalArgumentException("Couldn't read data:\t" + e.getMessage());
    } catch (NotTransformableSQLFieldException e) {
        throw new IllegalArgumentException(
                "Couldn't read data because of unknown column sql-type:\t" + e.getMessage());
    } catch (NullPointerException e) {
        throw new IllegalArgumentException("Couldn't access resultSet:\t" + e.getMessage());
    }
}

From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageHandler.java

public SqlMessage handleMessage(final SqlMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    DataSource ds = appCtx.getBean(msg.getDatasource(), DataSource.class);
    JdbcTemplate tmpl = new JdbcTemplate(ds);

    String sql = msg.getSql();/* w w  w .  j  a va2s .c  o  m*/
    CallableStatementCreator stmtCreator = null;
    CallableStatementCallback<SqlMessage> callback = null;
    if (sql.startsWith("plugin:")) {
        // Use a plugin to get the sql
        String pluginName = (sql.contains("?") ? sql.substring(7, sql.indexOf('?')) : sql.substring(7));
        final Plugin plugin = groovyPluginManager.getPlugin(pluginName);
        Map<String, Object> vars = new LinkedHashMap<String, Object>();
        vars.put("message", msg);
        vars.put("datasource", ds);
        vars.put("listen", groovyClosureFactory.createListenClosure(msg));
        vars.put("mapreduce", groovyClosureFactory.createMapReduceClosure(msg));
        plugin.setContext(vars);

        // Execute this plugin
        plugin.run();

        Object o = plugin.get("sql");
        if (null != o && o instanceof Closure) {
            sql = ((Closure) o).call(msg).toString();
        } else if (o instanceof String || o instanceof GString) {
            sql = o.toString();
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to SQL statement.");
        }
        msg.setSql(sql);

        o = plugin.get("statementCreator");
        if (null != o && o instanceof Closure) {
            stmtCreator = new CallableStatementCreator() {
                public CallableStatement createCallableStatement(Connection con) throws SQLException {
                    Object obj = ((Closure) plugin.get("statementCreator")).call(new Object[] { con, msg });
                    log.debug("from plugin statementCreator: " + String.valueOf(obj));
                    return (CallableStatement) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCreator. Define a closure named 'statementCreator' in your plugin.");
        }

        o = plugin.get("callback");
        if (null != o && o instanceof Closure) {
            callback = new CallableStatementCallback<SqlMessage>() {
                public SqlMessage doInCallableStatement(CallableStatement cs)
                        throws SQLException, DataAccessException {
                    Object obj = ((Closure) plugin.get("callback")).call(new Object[] { cs, msg });
                    log.debug("from plugin callback: " + String.valueOf(obj));
                    return (SqlMessage) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCallback. Define a closure named 'callback' in your plugin.");
        }
    } else {
        stmtCreator = new CallableStatementCreator() {
            public CallableStatement createCallableStatement(Connection connection) throws SQLException {
                CallableStatement stmt = connection.prepareCall(msg.getSql());
                List<Object> params = msg.getParams();
                if (null != params) {
                    int index = 1;
                    for (Object obj : params) {
                        stmt.setObject(index++, obj);
                    }
                }
                return stmt;
            }
        };
        callback = new CallableStatementCallback<SqlMessage>() {
            public SqlMessage doInCallableStatement(CallableStatement callableStatement)
                    throws SQLException, DataAccessException {
                if (null == msg.getResults().getData()) {
                    msg.getResults().setData(new ArrayList<List<Object>>());
                }
                if (callableStatement.execute()) {
                    ResultSet results = callableStatement.getResultSet();

                    // Pull out column names
                    ResultSetMetaData meta = results.getMetaData();
                    String[] columns = new String[meta.getColumnCount()];
                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                        columns[i - 1] = meta.getColumnName(i);
                    }
                    msg.getResults().getColumnNames().addAll(Arrays.asList(columns));

                    int total = 0;
                    while (results.next()) {
                        List<Object> row = new ArrayList<Object>(columns.length);
                        for (int i = 1; i <= columns.length; i++) {
                            row.add(results.getObject(i));
                        }
                        msg.getResults().getData().add(row);
                        total++;
                    }
                    msg.getResults().setTotalRows(total);

                } else {
                    msg.getResults().getColumnNames().add("updateCount");
                    msg.getResults().setTotalRows(1);
                    List<Object> updCnt = new ArrayList<Object>(1);
                    updCnt.add(callableStatement.getUpdateCount());
                    msg.getResults().getData().add(updCnt);
                }
                return msg;
            }
        };
    }
    try {
        tmpl.setExceptionTranslator(appCtx.getBean(SQLExceptionTranslator.class));
    } catch (NoSuchBeanDefinitionException notfound) {
        // IGNORED
    }

    if (null != stmtCreator && null != callback) {
        try {
            tmpl.execute(stmtCreator, callback);
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            List<String> errors = new ArrayList<String>();
            errors.add(t.getMessage());
            Throwable cause = t.getCause();
            if (null != cause) {
                do {
                    errors.add(cause.getMessage());
                } while (null != (cause = cause.getCause()));
            }
            msg.getResults().setErrors(errors);
        }
    } else {
        log.warn("CallableStatementCreator and/or CallableStatementCallback where empty. "
                + "Make sure your plugin provides these under 'statementCreator' and 'callback' respectively.");
    }
    return msg;
}

From source file:jp.primecloud.auto.tool.management.db.SQLExecuter.java

public List<Map<String, Object>> showColumns(String sql) throws SQLException, Exception {
    Connection con = null;// w  w w.j  av a 2  s  .co  m
    Statement stmt = null;
    ResultSet rs = null;
    log.info("[" + sql + "] ???");
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    try {
        con = dbConnector.getConnection();
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        ResultSetMetaData rsMetaData = rs.getMetaData();

        int size = rsMetaData.getColumnCount();
        while (rs.next()) {
            Map<String, Object> result = new HashMap<String, Object>();
            for (int i = 1; i <= size; i++) {
                result.put(parseColumnName(rsMetaData.getColumnName(i)), rs.getObject(i));
            }
            results.add(result);
        }
        log.info("[" + sql + "] ????");
    } catch (SQLException e) {
        log.error(e.getMessage(), e);

        throw new SQLException(e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new Exception(e);
    } finally {
        try {
            dbConnector.closeConnection(con, stmt, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    return results;
}