Example usage for java.sql ResultSet getMetaData

List of usage examples for java.sql ResultSet getMetaData

Introduction

In this page you can find the example usage for java.sql ResultSet getMetaData.

Prototype

ResultSetMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves the number, types and properties of this ResultSet object's columns.

Usage

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}./* ww w.j  a  va 2s .  co  m*/
 * 
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static List<Object[]> runSql(Session session, final String queryString, final Object[] parameters) {
    final List<Object[]> result = new ArrayList<Object[]>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                ResultSet rs = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();
                    while (rs.next()) {
                        Object[] current = new Object[cc];
                        for (int i = 0; i < cc; i++) {
                            current[i] = rs.getObject(i + 1);
                        }
                        result.add(current);
                    }
                } finally {
                    if (null != rs) {
                        rs.close();
                    }
                    if (null != stmt) {
                        stmt.close();
                    }
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}

From source file:net.orpiske.ssps.common.db.CountRsHandler.java

@Override
public Integer handle(ResultSet rs) throws SQLException {
    Integer dto = null;/* w  ww . j a v a2s  .  com*/

    // No records to handle :O
    if (!rs.next()) {
        return null;
    }

    ResultSetMetaData meta = rs.getMetaData();

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        Object value = rs.getObject(i);

        try {
            if (value instanceof Integer) {
                dto = (Integer) value;
            }

        } catch (Exception e) {
            throw new SQLException("Unable to set/retrieve count value", e);
        }
    }

    return dto;
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}.//from  ww  w  .j a  v  a2  s.c  o  m
 * 
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
// hongliangpan add
public static List<Map<String, Object>> runSqlReturnMap(Session session, final String queryString,
        final Object[] parameters) {
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                ResultSet rs = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();

                    while (rs.next()) {
                        Map<String, Object> t_row = new LinkedHashMap<String, Object>();
                        for (int i = 0; i < cc; i++) {
                            Object t_value = rs.getObject(i + 1);
                            t_row.put(md.getColumnLabel(i + 1), t_value);
                        }
                        result.add(t_row);
                    }
                } finally {
                    if (null != rs) {
                        rs.close();
                    }
                    if (null != stmt) {
                        stmt.close();
                    }
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}

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

/**
 * Converts data from a {@link java.sql.ResultSet} into a {@link JSONArray} containing
 * one {@link JSONObject} per row//w  w w.ja v  a  2s . com
 * @param rs the result set containing the data to convert to JSON
 * @return a json array containing the data
 * @throws SQLException when iteration or access to {@code rs} fails
 */
protected JSONArray getJSONRows(ResultSet rs) throws SQLException {
    JSONArray rows = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    if (rsmd == null)
        rsmd = new RowSetMetaDataImpl();
    List<String> convertedResult = new ArrayList<>();
    while (rs.next()) {
        JSONObject row = new JSONObject();
        String colValue;
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String origColName = rsmd.getColumnName(i);
            if (!origColName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
                boolean harmonize = isHarmonized();
                boolean prune = harmonize
                        ? ((JSONObject) this.harmonyMap).has(Harmonizer.PRUNE)
                                && ((JSONObject) this.harmonyMap).getBoolean(Harmonizer.PRUNE)
                        : false;
                String col = origColName;
                if (harmonize) {
                    if (((JSONObject) this.harmonyMap).has(origColName)) {
                        col = ((JSONObject) this.harmonyMap).getString(origColName);
                    } else if (prune) {
                        col = "";
                    }
                }

                //TODO handle empty result set more intelligently
                // OLD WAY adds headers to empty object when rs is empty
                if (!"".equals(col)) {
                    if (null == rs.getString(origColName) || NULL.equals(rs.getString(origColName))) {
                        colValue = NULL_REPLACEMENT;
                    } else {
                        colValue = rs.getString(origColName);
                    }
                    row.put(col, colValue);
                }
            }

        }
        rows.put(row);
        convertedResult.add(row.toString());
    }
    if (rows.length() > 0) {
        for (String key : JSONObject.getNames(rows.getJSONObject(0))) {
            getYADAQueryResult().addConvertedHeader(key);
        }
        getYADAQueryResult().getConvertedResults().add(convertedResult);
    }
    return rows;
}

From source file:net.sf.jdmf.data.sources.jdbc.JDBCDataSource.java

/**
 * @see net.sf.jdmf.data.sources.DataSource#getAttributes()
 *//*from   w w  w. j  av  a2  s  . co  m*/
public Map<String, List<Comparable>> getAttributes() {
    Map<String, List<Comparable>> attributes = new LinkedHashMap<String, List<Comparable>>();

    try {
        Connection connection = DriverManager.getConnection(connectionString, userName, password);

        Statement statement = connection.createStatement();

        for (String query : queries) {
            ResultSet resultSet = statement.executeQuery(query);

            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            for (int i = 1; i <= columnCount; ++i) {
                String attributeName = metaData.getColumnName(i);
                List<Comparable> attributeValues = new ArrayList<Comparable>();

                attributes.put(attributeName, attributeValues);
            }

            while (resultSet.next()) {
                for (int i = 1; i <= columnCount; ++i) {
                    List<Comparable> attributeValues = attributes.get(metaData.getColumnName(i));

                    attributeValues.add(getValueAsComparable(resultSet.getObject(i)));
                }
            }

            resultSet.close();
        }

        statement.close();
        connection.close();
    } catch (SQLException e) {
        throw new DataSourceException("Could not retrieve data", e);
    }

    return attributes;
}

From source file:com.cloudera.sqoop.util.ResultSetPrinter.java

/**
 * Format the contents of the ResultSet into something that could be printed
 * neatly; the results are appended to the supplied StringBuilder.
 *//*w w  w.j  a  va 2 s  .c  om*/
public final void printResultSet(PrintWriter pw, ResultSet results) throws IOException {
    try {
        StringBuilder sbNames = new StringBuilder();
        int cols = results.getMetaData().getColumnCount();

        int[] colWidths = new int[cols];
        ResultSetMetaData metadata = results.getMetaData();
        sbNames.append(LEFT_BORDER);
        for (int i = 1; i < cols + 1; i++) {
            String colName = metadata.getColumnName(i);
            colWidths[i - 1] = Math.min(metadata.getColumnDisplaySize(i), MAX_COL_WIDTH);
            if (colName == null || colName.equals("")) {
                colName = metadata.getColumnLabel(i) + "*";
            }
            printPadded(sbNames, colName, colWidths[i - 1]);
            sbNames.append(COL_SEPARATOR);
        }
        sbNames.append('\n');

        StringBuilder sbPad = new StringBuilder();
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < COL_SEPARATOR.length() + colWidths[i]; j++) {
                sbPad.append('-');
            }
        }
        sbPad.append('-');
        sbPad.append('\n');

        pw.print(sbPad.toString());
        pw.print(sbNames.toString());
        pw.print(sbPad.toString());

        while (results.next()) {
            StringBuilder sb = new StringBuilder();
            sb.append(LEFT_BORDER);
            for (int i = 1; i < cols + 1; i++) {
                printPadded(sb, results.getString(i), colWidths[i - 1]);
                sb.append(COL_SEPARATOR);
            }
            sb.append('\n');
            pw.print(sb.toString());
        }

        pw.print(sbPad.toString());
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + StringUtils.stringifyException(sqlException));
    }
}

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 {//from w  ww .  jav  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 {// w  w  w.ja  v  a2s .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.aw.core.util.QTTbBnMapperBasicRowProcessor.java

private void initForBean(ResultSet rs) throws SQLException {
    if (!beanMapper.isMetatadaBuilt()) {
        ResultSetMetaData metaData = rs.getMetaData();
        List colNames = new ArrayList();
        for (int i = 0; i < metaData.getColumnCount(); i++) {
            String colName = metaData.getColumnName(i + 1);
            colNames.add(colName);//ww  w.  ja va 2  s.  co m
        }

        beanMapper.buildMetadata(colNames);
        dataRowProvider = new BeanDataRowProvider(rs);
    }
}

From source file:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson6a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from  w ww .  j  a  v a 2s .c  o m
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";

        try {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet results = statement.executeQuery(query);

            if ((results != null) && (results.first())) {
                ResultSetMetaData resultsMetaData = results.getMetaData();
                StringBuffer output = new StringBuffer();

                output.append(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 5) {
                    return trackProgress(success().feedback("sql-injection.6a.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }

            } else {
                return trackProgress(failed().feedback("sql-injection.6a.no.results").build());

            }
        } catch (SQLException sqle) {
            return trackProgress(failed().output(sqle.getMessage()).build());
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage()).build());
    }
}