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:org.schedoscope.metascope.util.HiveQueryExecutor.java

@Transactional
public HiveQueryResult executeQuery(String databaseName, String tableName, String fields,
        Set<MetascopeField> parameters, Map<String, String> params) {
    List<List<String>> rows = new ArrayList<List<String>>();

    HiveServerConnection hiveConn = new HiveServerConnection(config);

    hiveConn.connect();/*from w ww.  j  av a  2 s.c  o  m*/

    if (hiveConn.getConnection() == null) {
        return new HiveQueryResult("Could not connect to HiveServer2");
    }

    String where = "";
    List<String> values = new ArrayList<String>();
    if (params != null) {
        for (Entry<String, String> param : params.entrySet()) {
            if (param.getKey().equals("fqdn") || param.getKey().equals("_csrf")) {
                continue;
            }
            if (!param.getValue().isEmpty()) {
                boolean parameterExists = false;
                for (MetascopeField parameter : parameters) {
                    if (parameter.getFieldName().equals(param.getKey())) {
                        parameterExists = true;
                    }
                }
                if (!parameterExists) {
                    hiveConn.close();
                    return new HiveQueryResult("Query not allowed");
                }

                if (!where.isEmpty()) {
                    where += " AND ";
                }
                where += param.getKey() + "=?";
                values.add(param.getValue());
            }
        }
    }

    String sql = " SELECT " + fields;
    String parameterList = "";
    for (MetascopeField parameter : parameters) {
        sql += "," + parameter.getFieldName();
    }
    sql += parameterList;
    sql += " FROM " + databaseName + "." + tableName;
    sql += where.isEmpty() ? "" : " WHERE " + where;
    sql += " LIMIT 10";

    List<String> header = new ArrayList<String>();
    try {
        PreparedStatement pstmt = hiveConn.getConnection().prepareStatement(sql);
        for (int i = 1; i <= values.size(); i++) {
            pstmt.setString(i, values.get(i - 1));
        }
        ResultSet rs = pstmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();

        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            header.add(rsmd.getColumnName(i));
        }

        while (rs.next()) {
            List<String> row = new ArrayList<String>();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                Object val = rs.getObject(i);
                String strVal = (val == null ? null : val.toString());
                row.add(strVal);
            }
            rows.add(row);
        }
    } catch (SQLException e) {
        LOG.error("Could not execute query", e);
        hiveConn.close();
        return new HiveQueryResult(e.getMessage());
    }

    hiveConn.close();
    return new HiveQueryResult(header, rows);
}

From source file:com.jaspersoft.jasperserver.war.CSVServlet.java

private void printCSV(ResultSet rs, PrintWriter out) throws Exception {
    ResultSetMetaData md = rs.getMetaData();
    int numCols = md.getColumnCount();

    // print column headers
    for (int i = 1; i < numCols; i++) {
        out.write(quoteString(md.getColumnName(i)));
        out.write(SEP);//from w  w w.java 2  s.co  m
    }
    out.write(quoteString(md.getColumnName(numCols)));
    out.write(NEWLINE);

    // print row data
    while (rs.next()) {
        for (int i = 1; i < numCols; i++) {
            out.write(quoteString("" + rs.getObject(i)));
            out.write(SEP);
        }
        out.write(quoteString("" + rs.getObject(numCols)));
        out.write(NEWLINE);
    }
}

From source file:com.streamsets.pipeline.stage.executor.jdbc.TestJdbcQueryExecutor.java

/**
 * Validate structure of the result set (column names and types).
 *//*from ww  w.  j ava  2  s  . c o  m*/
public void assertResultSetStructure(ResultSet rs, Pair<String, Integer>... columns) throws Exception {
    ResultSetMetaData metaData = rs.getMetaData();
    Assert.assertEquals(Utils.format("Unexpected number of columns"), columns.length,
            metaData.getColumnCount());
    int i = 1;
    for (Pair<String, Integer> column : columns) {
        Assert.assertEquals(Utils.format("Unexpected name for column {}", i), column.getLeft(),
                metaData.getColumnName(i));
        Assert.assertEquals(Utils.format("Unexpected type for column {}", i), (int) column.getRight(),
                metaData.getColumnType(i));
        i++;
    }
}

From source file:com.gzj.tulip.jade.rowmapper.MapEntryColumnRowMapper.java

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

    // ?// ww  w. ja  va  2s  .  co  m
    if (rowNum == 0) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int nrOfColumns = rsmd.getColumnCount();
        if (nrOfColumns != 2) {
            throw new IncorrectResultSetColumnCountException(2, nrOfColumns);
        }

        if (StringUtils.isNotEmpty(keyColumn)) {
            keyColumnIndex = rs.findColumn(keyColumn);
            if (keyColumnIndex == 1) {
                valueColumnIndex = 2;
            } else if (keyColumnIndex == 2) {
                valueColumnIndex = 1;
            } else {
                throw new IllegalArgumentException(
                        String.format("wrong key name %s for method: %s ", keyColumn, modifier.getMethod()));
            }
            keyColumn = null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("keyIndex=%s; valueIndex=%s; for method: %s ", keyColumnIndex,
                    valueColumnIndex, modifier.getMethod()));
        }
    }

    //   JDBC ResultSet ?  Key
    Object key = JdbcUtils.getResultSetValue(rs, keyColumnIndex, keyType);
    if (key != null && !keyType.isInstance(key)) {
        ResultSetMetaData rsmd = rs.getMetaData();
        throw new TypeMismatchDataAccessException( // NL
                "Type mismatch affecting row number " + rowNum + " and column type '"
                        + rsmd.getColumnTypeName(keyColumnIndex) + "' expected type is '" + keyType + "'");
    }

    //   JDBC ResultSet ?  Value
    Object value = JdbcUtils.getResultSetValue(rs, valueColumnIndex, valueType);
    if (value != null && !valueType.isInstance(value)) {
        ResultSetMetaData rsmd = rs.getMetaData();
        throw new TypeMismatchDataAccessException( // NL
                "Type mismatch affecting row number " + rowNum + " and column type '"
                        + rsmd.getColumnTypeName(valueColumnIndex) + "' expected type is '" + valueType + "'");
    }

    // key?null??
    return new MapEntryImpl<Object, Object>(key, value);
}

From source file:de.iritgo.aktario.jdbc.LoadAllObjects.java

/**
 * Perform the command.//from  w  w w . j  av a  2s .co m
 */
public void perform() {
    if (properties.getProperty("type") == null) {
        Log.logError("persist", "LoadObjects", "The type of the objects to load wasn't specified");

        return;
    }

    final String type = ((String) properties.getProperty("type"));

    final AbstractIObjectFactory factory = (AbstractIObjectFactory) Engine.instance().getIObjectFactory();

    IObject sample = null;

    try {
        sample = factory.newInstance(type);
    } catch (NoSuchIObjectException ignored) {
        Log.logError("persist", "LoadObjects", "Attemting to load objects of unknown type '" + type + "'");

        return;
    }

    if (!DataObject.class.isInstance(sample)) {
        Log.logError("persist", "LoadObjects", "Attemting to load objects that are not persitable");

        return;
    }

    final BaseRegistry registry = Engine.instance().getBaseRegistry();

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    try {
        QueryRunner query = new QueryRunner(dataSource);

        ResultSetHandler resultSetHandler = properties.get("resultSetHandle") != null
                ? (ResultSetHandler) properties.get("resultSetHandler")
                : new ResultSetHandler() {
                    public Object handle(ResultSet rs) throws SQLException {
                        ResultSetMetaData meta = rs.getMetaData();

                        int numObjects = 0;

                        while (rs.next()) {
                            try {
                                DataObject object = (DataObject) factory.newInstance(type);

                                object.setUniqueId(rs.getLong("id"));

                                for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) {
                                    Map.Entry attribute = (Map.Entry) i.next();

                                    if (attribute.getValue() instanceof IObjectList) {
                                        //                               loadList (
                                        //                                  dataSource, object,
                                        //                                  object.getIObjectListAttribute (
                                        //                                     (String) attribute.getKey ()));
                                    } else {
                                        object.setAttribute((String) attribute.getKey(),
                                                rs.getObject((String) attribute.getKey()));
                                    }
                                }

                                registry.add(object);
                                ++numObjects;
                            } catch (NoSuchIObjectException ignored) {
                            }
                        }

                        return new Integer(numObjects);
                    }
                };

        Object numObjects = query.query("select * from " + type, resultSetHandler);

        Log.logVerbose("persist", "LoadObjects",
                "Successfully loaded " + numObjects + " objects of type '" + type + "'");
    } catch (Exception x) {
        Log.logError("persist", "LoadObjects", "Error while loading objects of type '" + type + "': " + x);
    }
}

From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java

/**
 * The method prepares table's data in the shape and passes every {@link Row} into given RowProcessor.
 * //w  ww .  j a  v a  2s. c om
 * @param processor
 *            injected logic to perform some actions under passing rows. see details for {@link RowProcessor}.
 * @throws SQLException
 *             if any errors during work with database occur.
 */
public void getData(final RowProcessor processor) throws SQLException {
    try {
        jdbcTemplate.query(SELECT_FROM + tableName, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();

                Row row = new Row();
                for (int i = 1; i <= columnCount; i++) {
                    ColumnMetaData columnMetaData = ColumnMetaData.getInstance(metaData.getColumnName(i),
                            SqlTypes.getSqlTypeByJdbcSqlType(metaData.getColumnType(i)));
                    row.addCell(columnMetaData, rs.getObject(i));
                }
                try {
                    processor.process(row);
                } catch (RowProcessingException e) {
                    throw new SQLException(e);
                }
            }
        });

    } catch (DataAccessException e) {
        throw new SQLException(e);
    }
}

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

protected AttackResult injectableQuery(String accountName) {
    try {//from w  w  w . jav  a  2s.  c om
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE userid = " + accountName;

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

            if ((results != null) && (results.first() == true)) {
                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() >= 6) {
                    return trackProgress(success().feedback("sql-injection.5b.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }

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

                //                    output.append(getLabelManager().get("NoResultsMatched"));
            }
        } 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());
    }
}

From source file:com.itdaoshi.discuz.dao.CdbUcMembersDAObject.java

@Override
protected Long getNextPrimaryID() {
    QueryRunner run = new QueryRunner();
    ResultSetHandler h = new ResultSetHandler() {
        public Object handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return null;
            }//  ww  w .  j a  v  a  2s . c om

            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;
        }
    };
    try {
        Object[] result = (Object[]) run.query(conn, "SELECT MAX(uid) FROM CDB_UC_MEMBERS ", h);
        return (Long) result[0] + 1;
        // do something with the result
    } catch (Exception e) {
        e.printStackTrace();

    }

    return null;
}

From source file:com.gdo.project.util.SqlUtils.java

/**
 * Tests if a column exists in the result set.
 * /*from www. j  a  va  2 s  . com*/
 * @param field
 *            the label column searched.
 * @param rs
 *            the result set.
 * @return <tt>true</tt> if the column exists, <tt>false</tt> otherwise.
 */
public static boolean hasColumn(String field, ResultSet rs) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    int numCol = meta.getColumnCount();

    for (int i = 1; i < numCol + 1; i++) {
        if (meta.getColumnLabel(i).equals(field)) {
            return true;
        }
    }
    return false;
}

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

/**
 * Constructs an xml fragment of {@code ROW} elements with the result set data
 * @param rs the result set containing the data to be converted
 * @return a {@link DocumentFragment} containing the result data wrapped in XML
 * @throws SQLException when {@code rs} cannot be iterated or accessed
 */// ww  w  .  j av  a 2 s.co  m
private DocumentFragment getXMLRows(ResultSet rs) throws SQLException {
    DocumentFragment rows = this.doc.createDocumentFragment();

    ResultSetMetaData rsmd = rs.getMetaData();
    if (rsmd == null)
        rsmd = new RowSetMetaDataImpl();
    while (rs.next()) {
        Element row = this.doc.createElement(ROW);
        String colValue;
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String colName = rsmd.getColumnName(i);
            if (!colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
                String col = isHarmonized() && ((JSONObject) this.harmonyMap).has(colName)
                        ? ((JSONObject) this.harmonyMap).getString(colName)
                        : colName;
                if (null == rs.getString(colName) || NULL.equals(rs.getString(colName))) {
                    colValue = NULL_REPLACEMENT;
                } else {
                    colValue = rs.getString(colName);
                }
                Element column = this.doc.createElement(col);
                Text value = this.doc.createTextNode(colValue);
                column.appendChild(value);
                row.appendChild(column);
            }
        }
        rows.appendChild(row);
    }
    return rows;

}