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:io.lightlink.spring.StreamingMapper.java

private void readMetadata(ResultSet resultSet) throws SQLException {
    ResultSetMetaData metaData = resultSet.getMetaData();
    colCount = metaData.getColumnCount();
    colNames = new String[colCount];
    for (int i = 0; i < colNames.length; i++) {
        colNames[i] = metaData.getColumnLabel(i + 1);
    }//from w  w w . j  ava2 s  . com
}

From source file:com.p5solutions.core.jpa.orm.rowbinder.BasicTypeRowBinder.java

@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
    ResultSetMetaData metaData = rs.getMetaData();

    // / obviously if we have more than one column, we cannot possibly
    // map it/*ww  w  . j a  v a  2s  . co  m*/
    // / to a plain old java object of type Object.class, since there
    // are no
    // / members to map the columns to!
    if (metaData.getColumnCount() > 1) {
        throw new RuntimeException("Cannot return multi-column resultset into "
                + "a plain object of type Object.class. If you need to map a multi-column "
                + "resultset, please use an object marked with @" + Entity.class + " annotation.");
    }

    // // THIS SHOULD NEVER HAPPEN, QUERY EXCEPTION SHOULD
    // // BE THROWN IF THERE IS A SYNTAX ERROR IN THE QUERY.
    // if (metaData.getColumnCount() == 0) { }

    // Otherwise if there is only 1 column, and its within the scope of
    // plain object.class
    // returnResults.add((T)rs.getObject(1));
    return (T) rs.getObject(1);
}

From source file:com.modelmetrics.cloudconverter.engine.PicklistProviderSqlImpl.java

public List<String> getPicklistValues() throws Exception {

    log.debug("dirtconnection? " + connection.getClass().getName());

    Statement statement = connection.createStatement();

    //      String sql = (String) migrationContext.getPicklistFields()
    //            .get(current.getName());

    log.info("Picklist sql: " + sql);

    ResultSet rs = statement.executeQuery(sql);

    if (rs.getMetaData().getColumnCount() != 1) {
        rs.close();//from   ww w .j  a  va2s . c o  m
        statement.close();
        throw new RuntimeException(
                "Column count not right on picklist; should be 1 but is " + rs.getMetaData().getColumnCount());
    }
    ArrayList<String> values = new ArrayList<String>();

    while (rs.next()) {
        log.debug("picklist value is: " + rs.getString(1));
        values.add(rs.getString(1));
    }

    rs.close();
    statement.close();

    return values;

}

From source file:com.googlecode.datasourcetester.server.DataSourceTesterServiceImpl.java

public String[][] queryDataSource(String dataSourceJndiName, String query) {
    Connection conn = null;// w w w .  ja  va  2s.  c om
    try {
        InitialContext jndiContext = new InitialContext();
        DataSource ds = (DataSource) jndiContext.lookup(dataSourceJndiName);
        conn = ds.getConnection();
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData resMeta = rs.getMetaData();
        LinkedList<String[]> rowList = new LinkedList<String[]>();
        String[] colLabels = new String[resMeta.getColumnCount()];
        for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
            colLabels[colNr - 1] = resMeta.getColumnName(colNr);
        }
        rowList.add(colLabels);
        while (rs.next()) {
            String[] rowData = new String[resMeta.getColumnCount()];
            for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
                rowData[colNr - 1] = rs.getString(colNr);
            }
            rowList.add(rowData);
        }
        conn.close();
        return rowList.toArray(new String[rowList.size()][]);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException sqlEx) {
            logger.error(sqlEx.getMessage(), sqlEx);
        }
        return null;
    }
}

From source file:com.livinglogic.dbutils.ResultSetMapIterator.java

public ResultSetMapIterator(ResultSet resultSet) {
    this.resultSet = resultSet;
    try {//  ww  w  .j a  va 2s. c  o  m
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
    nextRecord = null;
    fetch();
}

From source file:MainClass.java

public void setQuery(String q) {
    cache = new Vector();
    try {//from  ww w  .ja v  a2  s. c o  m
        ResultSet rs = statement.executeQuery(q);
        ResultSetMetaData meta = rs.getMetaData();
        colCount = meta.getColumnCount();

        headers = new String[colCount];
        for (int h = 1; h <= colCount; h++) {
            headers[h - 1] = meta.getColumnName(h);
        }

        while (rs.next()) {
            String[] record = new String[colCount];
            for (int i = 0; i < colCount; i++) {
                record[i] = rs.getString(i + 1);
            }
            cache.addElement(record);
        }
        fireTableChanged(null);
    } catch (Exception e) {
        cache = new Vector();
        e.printStackTrace();
    }
}

From source file:org.jasig.services.persondir.support.jdbc.ColumnMapParameterizedRowMapper.java

public final Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
    final ResultSetMetaData rsmd = rs.getMetaData();
    final int columnCount = rsmd.getColumnCount();
    final Map<String, Object> mapOfColValues = this.createColumnMap(columnCount);

    for (int i = 1; i <= columnCount; i++) {
        final String columnName = JdbcUtils.lookupColumnName(rsmd, i);
        final Object obj = this.getColumnValue(rs, i);
        if (!this.ignoreNull || obj != null) {
            final String key = this.getColumnKey(columnName);
            mapOfColValues.put(key, obj);
        }//from  w  ww. j a  v a2  s .c om
    }

    return mapOfColValues;
}

From source file:edu.stanford.junction.sample.sql.QueryHandler.java

@Override
public void onMessageReceived(MessageHeader header, JSONObject message) {

    //String query = q.getQueryText();
    String query = message.optString("query");

    query = query.toLowerCase();//from  www.  j av  a2 s . c o m

    if (!query.contains("select"))
        return;
    if (query.contains("drop") || query.contains("delete"))
        return;
    System.out.println("Got query: " + query);

    Connection connection = null;
    try {
        // Load the JDBC driver
        String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
        Class.forName(driverName);

        // Create a connection to the database
        //String serverName = "192.168.1.122";
        String serverName = "127.0.0.1";
        String mydatabase = "jinzora3";
        String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
        String username = "jinzora";
        String password = "jinzora";
        connection = DriverManager.getConnection(url, username, password);
    } catch (ClassNotFoundException e) {
        // Could not find the database driver
        e.printStackTrace();
    } catch (SQLException e) {
        // Could not connect to the database
        e.printStackTrace();
    }

    try {
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        ResultSetMetaData rsMetaData = rs.getMetaData();
        int cols = rsMetaData.getColumnCount();

        while (rs.next()) {

            JSONObject row = new JSONObject();
            try {
                for (int i = 1; i <= cols; i++) { // stupid indexing
                    row.put(rsMetaData.getColumnName(i), rs.getObject(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            System.out.println("sending " + row);
            if (mActor != null) {
                //mActor.getJunction().sendMessageToTarget(header.getReplyTarget(),row);
                header.getReplyTarget().sendMessage(row);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    System.out.println("closing stream.");
    //results.close();
}

From source file:com.teradata.benchto.driver.execution.QueryExecutionDriver.java

private void logRow(int rowNumber, ResultSet resultSet) throws SQLException {
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    StringJoiner joiner = new StringJoiner("; ", "[", "]");
    for (int i = 1; i <= resultSetMetaData.getColumnCount(); ++i) {
        joiner.add(resultSetMetaData.getColumnName(i) + ": " + resultSet.getObject(i));
    }/*from   w  w w  .j av  a 2 s . com*/

    LOG.info("Row: " + rowNumber + ", column values: " + joiner.toString());
}

From source file:cherry.foundation.etl.ExtractorResultSetExtractor.java

@Override
public Long extractData(ResultSet rs) throws SQLException, DataAccessException {
    try {/*from w  w  w  .j  a va  2s .com*/

        ResultSetMetaData metaData = rs.getMetaData();
        Column[] col = new Column[metaData.getColumnCount()];
        for (int i = 1; i <= col.length; i++) {
            col[i - 1] = new Column();
            col[i - 1].setType(metaData.getColumnType(i));
            col[i - 1].setLabel(metaData.getColumnLabel(i));
        }

        consumer.begin(col);

        long count;
        for (count = 0L; rs.next(); count++) {

            Object[] record = new Object[col.length];
            for (int i = 1; i <= record.length; i++) {
                record[i - 1] = rs.getObject(i);
            }

            consumer.consume(record);
            limiter.tick();
        }

        consumer.end();
        return count;

    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}