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.zimbra.cs.db.JdbcClient.java

private Object[] getCurrentRow(ResultSet rs) throws SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int colCount = md.getColumnCount();
    Object[] row = new Object[colCount];
    for (int i = 0; i < colCount; i++) {
        row[i] = rs.getObject(i + 1);/*from  w  w  w  .  java  2s.  co m*/
    }
    return row;
}

From source file:com.netspective.sparx.form.DialogContextUtils.java

public void populateFieldValuesFromResultSet(DialogContext dc, ResultSet rs) throws SQLException {
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        DialogFieldStates fieldStates = dc.getFieldStates();
        for (int i = 1; i <= colsCount; i++) {
            String fieldName = rsmd.getColumnName(i).toLowerCase();
            DialogField.State state = fieldStates.getState(fieldName, null);
            if (state != null) {
                // for columns that are Date objects, use the object setter instead of the text setter
                // because we don't need to do unnecessary formatting/parsing
                if (rsmd.getColumnType(i) == Types.DATE)
                    state.getValue().setValue(rs.getDate(i));
                else
                    state.getValue().setTextValue(rs.getString(i));
            }/*from   w w w  .j  a  va2  s.c  o  m*/
        }
    }
}

From source file:com.opencsv.ResultSetHelperService.java

@Override
public String[] getColumnValues(ResultSet rs, boolean trim, String dateFormatString, String timeFormatString)
        throws SQLException, IOException {
    ResultSetMetaData metadata = rs.getMetaData();
    String[] valueArray = new String[metadata.getColumnCount()];
    for (int i = 1; i <= metadata.getColumnCount(); i++) {
        valueArray[i - 1] = getColumnValue(rs, metadata.getColumnType(i), i, trim, dateFormatString,
                timeFormatString);/*from ww w.j  a  v a  2  s . c  om*/
    }
    return valueArray;
}

From source file:com.itdaoshi.dokeos.dao.UserDAObject.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;
            }//from  w  w w . j av  a2s  . c  o m

            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(user_id) FROM USER ", h);
        return (Long) result[0] + 1;
        // do something with the result
    } catch (Exception e) {
        e.printStackTrace();

    }

    return null;

}

From source file:co.nubetech.hiho.mapreduce.lib.db.apache.DateSplitter.java

public List<InputSplit> split(Configuration conf, ResultSet results, String colName) throws SQLException {

    long minVal;/*from   www . j  av a 2s .co m*/
    long maxVal;

    int sqlDataType = results.getMetaData().getColumnType(1);
    minVal = resultSetColToLong(results, 1, sqlDataType);
    maxVal = resultSetColToLong(results, 2, sqlDataType);

    String lowClausePrefix = colName + " >= ";
    String highClausePrefix = colName + " < ";

    int numSplits = conf.getInt(MRJobConfig.NUM_MAPS, 1);
    if (numSplits < 1) {
        numSplits = 1;
    }

    if (minVal == Long.MIN_VALUE && maxVal == Long.MIN_VALUE) {
        // The range of acceptable dates is NULL to NULL. Just create a single split.
        List<InputSplit> splits = new ArrayList<InputSplit>();
        splits.add(
                new DataDrivenDBInputFormat.DataDrivenDBInputSplit(colName + " IS NULL", colName + " IS NULL"));
        return splits;
    }

    // Gather the split point integers
    List<Long> splitPoints = split(numSplits, minVal, maxVal);
    List<InputSplit> splits = new ArrayList<InputSplit>();

    // Turn the split points into a set of intervals.
    long start = splitPoints.get(0);
    Date startDate = longToDate(start, sqlDataType);
    if (sqlDataType == Types.TIMESTAMP) {
        // The lower bound's nanos value needs to match the actual lower-bound nanos.
        try {
            ((java.sql.Timestamp) startDate).setNanos(results.getTimestamp(1).getNanos());
        } catch (NullPointerException npe) {
            // If the lower bound was NULL, we'll get an NPE; just ignore it and don't set nanos.
        }
    }

    for (int i = 1; i < splitPoints.size(); i++) {
        long end = splitPoints.get(i);
        Date endDate = longToDate(end, sqlDataType);

        if (i == splitPoints.size() - 1) {
            if (sqlDataType == Types.TIMESTAMP) {
                // The upper bound's nanos value needs to match the actual upper-bound nanos.
                try {
                    ((java.sql.Timestamp) endDate).setNanos(results.getTimestamp(2).getNanos());
                } catch (NullPointerException npe) {
                    // If the upper bound was NULL, we'll get an NPE; just ignore it and don't set nanos.
                }
            }
            // This is the last one; use a closed interval.
            splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit(
                    lowClausePrefix + dateToString(startDate), colName + " <= " + dateToString(endDate)));
        } else {
            // Normal open-interval case.
            splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit(
                    lowClausePrefix + dateToString(startDate), highClausePrefix + dateToString(endDate)));
        }

        start = end;
        startDate = endDate;
    }

    if (minVal == Long.MIN_VALUE || maxVal == Long.MIN_VALUE) {
        // Add an extra split to handle the null case that we saw.
        splits.add(
                new DataDrivenDBInputFormat.DataDrivenDBInputSplit(colName + " IS NULL", colName + " IS NULL"));
    }

    return splits;
}

From source file:ca.fastenalcompany.jsonconfig.ProductJson.java

/**
 * Produces a basic JSON Object using the JSON Object API
 *
 * @return - The JSON Object/* ww  w.j a v a  2  s.co m*/
 */
public JSONArray query(String query, String... params) {
    Connection conn = null;
    JSONArray products = new JSONArray();
    try {
        conn = DBManager.getMysqlConn();
        PreparedStatement pstmt = conn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }
        System.out.println(query);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            JSONObject product = new JSONObject();
            for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
                String label = rs.getMetaData().getColumnLabel(i);
                String value = rs.getString(label);
                product.put(label, value);
            }
            products.add(product);
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            System.out.println(PropertyManager.getProperty("db_conn_closed"));
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return products;
}

From source file:uk.org.rbc1b.roms.controller.report.ReportsController.java

private ReportResults extractResults(String sql) throws SQLException {
    Connection con = DataSourceUtils.getConnection(dataSource);
    Statement s = con.createStatement();

    ResultSet rs = s.executeQuery(sql);

    ReportResults reportResults = new ReportResults();

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

    List<Integer> columnTypeIds = new ArrayList<Integer>();
    for (int i = 0; i < columnCount; i++) {
        columnTypeIds.add(rsmd.getColumnType(i + 1));
    }/*  www . ja  v a  2  s. co m*/

    reportResults.columnNames = new ArrayList<String>();
    for (int i = 0; i < columnCount; i++) {
        reportResults.columnNames.add(rsmd.getColumnLabel(i + 1));
    }

    reportResults.resultRows = new ArrayList<List<String>>();
    while (rs.next()) {
        List<String> resultRow = new ArrayList<String>();

        for (int i = 0; i < columnCount; i++) {
            Integer columnTypeId = columnTypeIds.get(i);
            if (columnTypeId.intValue() == Types.BOOLEAN || columnTypeId.intValue() == Types.BIT) {
                resultRow.add(Boolean.valueOf(rs.getBoolean(i + 1)).toString());
            } else {
                resultRow.add(rs.getString(i + 1));
            }
        }

        reportResults.resultRows.add(resultRow);
    }

    return reportResults;
}

From source file:at.ac.univie.isc.asio.engine.sql.WebRowSetWriter.java

private ResultSetMetaData context() throws SQLException {
    final ResultSet rs = cursor.resultSet();
    if (rs == null) {
        throw new JooqEngine.Cancelled();
    }/*w  w w . j a v  a 2s. c  om*/
    return rs.getMetaData();
}

From source file:JDBCExecutor.java

public void executeStatement(String sql) {

    LOG("Executing query: " + sql);
    try (Connection connection = getConnection()) {
        Statement stmt = connection.createStatement();
        LOG("\t Time taken to create statement : ");

        ResultSet rs = stmt.executeQuery(sql);
        LOG("\t Time taken to execute query : ");
        if (rs == null) {
            return;
        }//from  w  ww.j  a  v a2 s .c  o m

        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        LOG("\t\t Time taken to get resultset metadata: ");

        boolean processedFirstRecord = false;
        while (rs.next()) {
            for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                Object colObj = rs.getObject(i);
            }
            if (!processedFirstRecord) {
                processedFirstRecord = true;
                LOG("\t\t Processed first record : ");
            }
        }
        LOG("\t\t Processed all records : ");

        rs.close();
        LOG("\t\t Closed resultSet : ");
    } catch (SQLException e) {
        LOG("Error executing query", e);
    }
    LOG("\t Closed connection : ");
}

From source file:com.cloudera.sqoop.mapreduce.db.DateSplitter.java

public List<InputSplit> split(Configuration conf, ResultSet results, String colName) throws SQLException {

    long minVal;//w w w . jav  a 2  s.com
    long maxVal;

    int sqlDataType = results.getMetaData().getColumnType(1);
    minVal = resultSetColToLong(results, 1, sqlDataType);
    maxVal = resultSetColToLong(results, 2, sqlDataType);

    String lowClausePrefix = colName + " >= ";
    String highClausePrefix = colName + " < ";

    int numSplits = ConfigurationHelper.getConfNumMaps(conf);
    if (numSplits < 1) {
        numSplits = 1;
    }

    if (minVal == Long.MIN_VALUE && maxVal == Long.MIN_VALUE) {
        // The range of acceptable dates is NULL to NULL. Just create a single
        // split.
        List<InputSplit> splits = new ArrayList<InputSplit>();
        splits.add(
                new DataDrivenDBInputFormat.DataDrivenDBInputSplit(colName + " IS NULL", colName + " IS NULL"));
        return splits;
    }

    // Gather the split point integers
    List<Long> splitPoints = split(numSplits, minVal, maxVal);
    List<InputSplit> splits = new ArrayList<InputSplit>();

    // Turn the split points into a set of intervals.
    long start = splitPoints.get(0);
    Date startDate = longToDate(start, sqlDataType);
    if (sqlDataType == Types.TIMESTAMP) {
        // The lower bound's nanos value needs to match the actual lower-bound
        // nanos.
        try {
            ((java.sql.Timestamp) startDate).setNanos(results.getTimestamp(1).getNanos());
        } catch (NullPointerException npe) {
            // If the lower bound was NULL, we'll get an NPE; just ignore it and
            // don't set nanos.
        }
    }

    for (int i = 1; i < splitPoints.size(); i++) {
        long end = splitPoints.get(i);
        Date endDate = longToDate(end, sqlDataType);

        if (i == splitPoints.size() - 1) {
            if (sqlDataType == Types.TIMESTAMP) {
                // The upper bound's nanos value needs to match the actual
                // upper-bound nanos.
                try {
                    ((java.sql.Timestamp) endDate).setNanos(results.getTimestamp(2).getNanos());
                } catch (NullPointerException npe) {
                    // If the upper bound was NULL, we'll get an NPE; just ignore it
                    // and don't set nanos.
                }
            }
            // This is the last one; use a closed interval.
            splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit(
                    lowClausePrefix + dateToString(startDate), colName + " <= " + dateToString(endDate)));
        } else {
            // Normal open-interval case.
            splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit(
                    lowClausePrefix + dateToString(startDate), highClausePrefix + dateToString(endDate)));
        }

        start = end;
        startDate = endDate;
    }

    if (minVal == Long.MIN_VALUE || maxVal == Long.MIN_VALUE) {
        // Add an extra split to handle the null case that we saw.
        splits.add(
                new DataDrivenDBInputFormat.DataDrivenDBInputSplit(colName + " IS NULL", colName + " IS NULL"));
    }

    return splits;
}