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:net.mindengine.oculus.frontend.db.jdbc.BeanMapper.java

@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    // TODO Auto-generated method stub
    ResultSetMetaData metaData = rs.getMetaData();
    int columns = metaData.getColumnCount();
    try {/*from   ww  w .j  a  va2 s.co  m*/
        Class<?> clazz = Class.forName(className);

        Object obj = clazz.newInstance();
        for (int i = 1; i <= columns; i++) {
            String column = metaData.getColumnName(i);
            FieldMapper fm = fields.get(column);
            if (fm != null) {
                Method method = fm.getMethod();

                String typeName = fm.getType().getSimpleName();

                typeName = StringUtils.capitalize(typeName);
                if (typeName.endsWith("[]")) {
                    typeName = typeName.substring(0, typeName.length() - 2) + "s";
                }
                if (typeName.equals("Date")) {
                    typeName = "Timestamp";
                }
                if (typeName.equals("Integer")) {
                    typeName = "Int";
                }

                Method rsMethod = ResultSet.class.getMethod("get" + typeName, String.class);
                Object value = rsMethod.invoke(rs, column);

                if (value instanceof Timestamp) {
                    Timestamp timestamp = (Timestamp) value;
                    value = new Date(timestamp.getTime());
                }
                method.invoke(obj, value);
            }
        }
        return obj;
    } catch (Exception e) {
        throw new SQLException(e);
    }
}

From source file:net.orpiske.ssps.common.dependencies.cache.MultiRsHandler.java

@Override
protected DependencyCacheDto handleRow(ResultSet rs) throws SQLException {
    DependencyCacheDto dto = new DependencyCacheDto();

    ResultSetMetaData meta = rs.getMetaData();

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

        try {/*from ww w.  ja  v a  2s .  c o  m*/
            /*
             * We convert the column name to a more appropriate and java like name 
             * because some columns are usually named as some_thing whereas Java 
             * properties are named someThing. This call does this conversion.
             */
            String javaProperty = NameConverter.sqlToProperty(name);

            if (javaProperty.equals("version")) {
                Version version = Version.toVersion((String) value);

                PropertyUtils.setSimpleProperty(dto, javaProperty, version);
            } else {
                PropertyUtils.setSimpleProperty(dto, javaProperty, value);
            }
        } catch (Exception e) {
            throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e);
        }
    }

    return dto;
}

From source file:com.job.portal.utils.AbstractDAO.java

protected JSONObject getJSONObject(ResultSet rs) throws SQLException, JSONException {
    JSONObject obj = null;/*from  ww  w .  java2s .co m*/
    ResultSetMetaData rsmd = rs.getMetaData();
    int size = rsmd.getColumnCount();
    if (rs.next()) {
        obj = new JSONObject();
        for (int i = 1; i <= size; i++) {
            obj.put(rsmd.getColumnName(i), rs.getString(i));
        }
    }
    return obj;
}

From source file:ResultsDecoratorHTML.java

public void write(ResultSet rs) throws IOException, SQLException {

    ResultSetMetaData md = rs.getMetaData();
    int count = md.getColumnCount();
    println("<table border=1>");
    print("<tr>");
    for (int i = 1; i <= count; i++) {
        print("<th>");
        print(md.getColumnLabel(i));/*from www .  j a va  2  s .c o m*/
    }
    println("</tr>");
    while (rs.next()) {
        print("<tr>");
        for (int i = 1; i <= count; i++) {
            print("<td>");
            print(rs.getString(i));
        }
        println("</tr>");
    }
    println("</table>");
}

From source file:jongo.handler.ResultSetMetaDataHandler.java

@Override
public List<Row> handle(ResultSet rs) throws SQLException {
    List<Row> results = new ArrayList<Row>();
    int rowId = 0;
    ResultSetMetaData metaData = rs.getMetaData();
    Map<String, String> map = null;
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        map = new HashMap<String, String>(2);
        map.put("tableName", metaData.getTableName(i));
        map.put("columnName", metaData.getColumnName(i));
        map.put("columnLabel", metaData.getColumnLabel(i));
        map.put("columnType", metaData.getColumnTypeName(i));
        map.put("columnSize", String.valueOf(metaData.getColumnDisplaySize(i)));
        map.put("precision", String.valueOf(metaData.getPrecision(i)));
        map.put("scale", String.valueOf(metaData.getScale(i)));

        //            map.put("catalog_name", metaData.getCatalogName(i));
        //            map.put("column_class_name", metaData.getColumnClassName(i));
        //            map.put("schema_name", metaData.getSchemaName(i));
        //            map.put("column_type", String.valueOf(metaData.getColumnType(i)));

        if (map != null)
            results.add(new Row(rowId++, map));
    }/* w w  w .jav  a  2s  .c  o  m*/
    return results;
}

From source file:net.orpiske.ssps.common.registry.MultiRsHandler.java

@Override
protected SoftwareInventoryDto handleRow(ResultSet rs) throws SQLException {
    SoftwareInventoryDto dto = new SoftwareInventoryDto();

    ResultSetMetaData meta = rs.getMetaData();

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

        try {//from  w  w w . ja  va2 s  . co  m
            /*
             * We convert the column name to a more appropriate and java like name 
             * because some columns are usually named as some_thing whereas Java 
             * properties are named someThing. This call does this conversion.
             */
            String javaProperty = NameConverter.sqlToProperty(name);

            if (javaProperty.equals("version")) {
                Version version = Version.toVersion((String) value);

                PropertyUtils.setSimpleProperty(dto, javaProperty, version);
            } else {
                PropertyUtils.setSimpleProperty(dto, javaProperty, value);
            }
        } catch (Exception e) {
            throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e);
        }
    }

    return dto;
}

From source file:DatabaseTest.java

public void setQuery(String q) {
    cache = new Vector();
    try {/*  w w w.  j  a v  a2s.  c  o m*/
        // Execute the query and store the result set and its metadata
        ResultSet rs = statement.executeQuery(q);
        ResultSetMetaData meta = rs.getMetaData();
        colCount = meta.getColumnCount();

        // Now we must rebuild the headers array with the new column names
        headers = new String[colCount];
        for (int h = 1; h <= colCount; h++) {
            headers[h - 1] = meta.getColumnName(h);
        }

        // and file the cache with the records from our query. This would
        // not be
        // practical if we were expecting a few million records in response
        // to our
        // query, but we aren't, so we can do this.
        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); // notify everyone that we have a new table.
    } catch (Exception e) {
        cache = new Vector(); // blank it out and keep going.
        e.printStackTrace();
    }
}

From source file:cc.osint.graphd.db.SQLDB.java

private JSONObject jsonizeResultSet(ResultSet rs) throws Exception {
    List<JSONObject> results = new ArrayList<JSONObject>();
    ResultSetMetaData md = rs.getMetaData();
    int colmax = md.getColumnCount();
    int i;/*from  w  w w  . j a v a 2s .co m*/
    for (; rs.next();) {
        JSONObject result = new JSONObject();
        for (i = 1; i <= colmax; i++) {
            String colName = md.getColumnName(i).toLowerCase();
            String colClassName = md.getColumnClassName(i);
            String colType = md.getColumnTypeName(i);
            Object obj = rs.getObject(i);
            result.put(colName, obj);
            log.info(colName + ": " + colClassName + ": " + colType + ": " + obj.toString());
        }
        results.add(result);
    }
    JSONObject result = new JSONObject();
    result.put("results", results);
    return result;
}

From source file:de.static_interface.reallifeplugin.database.AbstractTable.java

public boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int x = 1; x <= columns; x++) {
        if (columnName.equals(rsmd.getColumnName(x))) {
            return true;
        }//from  ww  w. j  a v a 2  s.c o  m
    }
    return false;
}

From source file:org.schedoscope.metascope.service.MetascopeDataDistributionService.java

@Async("background")
public void calculateDistribution(MetascopeTable table) {
    runningJobs.put(table.getFqdn(), true);

    String sql = DataDistributionSqlUtil.buildSql(table);

    HiveServerConnection hiveConn = new HiveServerConnection(config);

    hiveConn.connect();/*from w w  w .ja  v a2s.c o  m*/

    if (hiveConn.getConnection() == null) {
        runningJobs.put(table.getFqdn(), false);
        return;
    }

    try {
        Statement stmt = hiveConn.getConnection().createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        ResultSetMetaData rsmd = rs.getMetaData();

        List<String> columnNames = new ArrayList<>();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            columnNames.add(rsmd.getColumnName(i));
        }

        long ts = System.currentTimeMillis();
        if (rs.next()) {
            for (String columnName : columnNames) {
                MetascopeDataDistribution mdd = new MetascopeDataDistribution();
                mdd.setId(table.getFqdn() + "." + columnName);
                mdd.setFqdn(table.getFqdn());
                mdd.setMetric(columnName);
                mdd.setValue(rs.getString(columnName));
                metascopeDataDistributionRepository.save(mdd);
            }
        }
    } catch (SQLException e) {
        hiveConn.close();
        runningJobs.put(table.getFqdn(), false);
        LOG.error("Could not execute hive query", e);
    }

    hiveConn.close();

    runningJobs.put(table.getFqdn(), false);
}