Example usage for java.sql ResultSetMetaData getColumnCount

List of usage examples for java.sql ResultSetMetaData getColumnCount

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnCount.

Prototype

int getColumnCount() throws SQLException;

Source Link

Document

Returns the number of columns in this ResultSet object.

Usage

From source file:net.mlw.vlh.adapter.jdbc.util.ResultSetMapGenerator.java

public ResultSetMapGenerator(ResultSet result, boolean useName, boolean lowerCase) throws SQLException {
    this.result = result;
    ResultSetMetaData metadata = result.getMetaData();

    int columnCount = metadata.getColumnCount();
    names = new String[columnCount];
    for (int i = 0; i < columnCount; i++) {
        names[i] = (useName) ? metadata.getColumnName(i + 1) : metadata.getColumnLabel(i + 1);
        if (names[i] == null || names[i].length() == 0) {
            names[i] = (useName) ? metadata.getColumnLabel(i + 1) : metadata.getColumnName(i + 1);
        }/*from   www. j  a va 2 s.  c  om*/

        if (lowerCase) {
            names[i] = names[i].toLowerCase();
        }
    }
    LOGGER.debug(names);
}

From source file:ca.on.gov.jus.icon.common.util.LookupNestedMapHandler.java

/**
 * Iterates through the query result set and creates a correctly
 * indexed map of maps.  This is only intended to work with a result
 * set that contains three columns and the first column must
 * cast successfully to a <code>Integer</code> datatype.
 * /*from w  w w  .j  a va2s  . com*/
 * @param   rs      The result set that is used to obtain the name/value data.
 * @return   Object   The <code>java.util.Map</code> collection containing the results. 
 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
 */
public Object handle(ResultSet rs) throws SQLException {
    Map results = new HashMap();
    Map nestedMap = new HashMap();
    Integer currentId = null;

    // Get the number of columns in the result set.
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();

    // Populate the Map with the name value pairs
    // if the result set contains two columns of data.
    if (cols == MAP_RESULT_SET_COLUMNS) {
        while (rs.next()) {
            Object primaryId = rs.getObject(1);
            Object secondaryId = rs.getObject(2);
            Object secondaryValue = rs.getObject(3);

            // Initialize the current id on the first iteration.
            if (currentId == null) {
                currentId = (Integer) primaryId;
            }

            // Check if the primary id is not the same as the current id.         
            if (currentId.compareTo(primaryId) != 0) {
                // Put the current nested map into the result map
                // and create a new nested map.
                results.put(currentId, nestedMap);
                nestedMap = new HashMap();
                currentId = (Integer) primaryId;
            }

            // Put the key & value into the current nested map.
            // This occurs after checking if a new nested map is required.
            nestedMap.put(secondaryId, secondaryValue);
        }

        // Put the final nested map into the results map
        // once the iterations are complete.
        results.put(currentId, nestedMap);
    }

    return results;
}

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  w  ww .  j  a v a 2 s .c om
    }
    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:com.linuxrouter.netcool.session.QueryUtils.java

public ArrayList<HashMap<String, Object>> executeQuery(String dbName, String sql) {
    Long start = System.currentTimeMillis();
    ArrayList<HashMap<String, Object>> result = new ArrayList<>();
    HashMap<Integer, String> colTypes = new HashMap<Integer, String>();
    HashMap<Integer, String> colNames = new HashMap<Integer, String>();
    try {/*from w  ww . jav  a2  s  .c  o m*/
        //connection caching...
        Connection con = null;
        if (connectionMap.get(dbName) == null) {
            BasicDataSource ds = DbUtils.getSimpleDataSourceByName(dbName);
            con = ds.getConnection();
            connectionMap.put(dbName, con);
        } else {
            con = connectionMap.get(dbName);

        }

        Statement st = con.createStatement();

        ResultSet rs = st.executeQuery(sql);
        ResultSetMetaData metaData = rs.getMetaData();
        int colCount = metaData.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            colTypes.put(i, metaData.getColumnTypeName(i));
            colNames.put(i, metaData.getColumnLabel(i));
        }
        while (rs.next()) {
            HashMap<String, Object> dado = new HashMap<>();
            for (int i = 1; i <= colCount; i++) {
                dado.put(colNames.get(i), rs.getObject(i));

            }
            result.add(dado);
        }
        rs.close();
        st.close();
        //con.close();
        Long end = System.currentTimeMillis();
        //logger.debug("Query on external DB took: " + (end - start) + "ms");
    } catch (SQLException ex) {
        logger.error("Erro ao executar query:", ex);
    }
    return result;
}

From source file:Professor.java

  public void checkData(String sql) throws Exception {
  ResultSet rs = st.executeQuery(sql);
  ResultSetMetaData metadata = rs.getMetaData();

  for (int i = 0; i < metadata.getColumnCount(); i++) {
    System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
  }//from  w w w  .j a va  2s .co  m
  System.out.println("\n----------------------------------");

  while (rs.next()) {
    for (int i = 0; i < metadata.getColumnCount(); i++) {
      Object value = rs.getObject(i + 1);
      if (value == null) {
        System.out.print("\t       ");
      } else {
        System.out.print("\t"+value.toString().trim());
      }
    }
    System.out.println("");
  }
}

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;
            }//w w w . j a v  a2s. com

            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: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;
        }/*  w  w  w .j a va2  s .co m*/
    }
    return false;
}

From source file:com.nilesh.GenericResourse.java

/**
 * Retrieves representation of an instance of com.nilesh.GenericResourse
 * @return an instance of java.lang.String
 *///from   w  ww  .ja  v a  2  s . c o m
@GET
@Path("/products")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<product> getXml()
        throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {

    //TODO return proper representation object

    Statement smt = conn.createStatement();
    ResultSet rs = smt.executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int col = rsmd.getColumnCount();
    while (rs.next()) {

        product pro = new product(rs.getInt("productid"), rs.getString("name"), rs.getString("description"),
                rs.getInt("quantity"));
        products.add(pro);
    }

    return products;
}

From source file:net.sf.jdbcwrappers.trim.TrimmingResultSetInvocationHandler.java

private void fetchCharColumns() throws SQLException {
    if (charColumns == null) {
        ResultSetMetaData metadata = target.getMetaData();
        int columnCount = metadata.getColumnCount();
        charColumns = new HashSet<String>();
        isCharColumn = new boolean[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            if (metadata.getColumnType(i) == Types.CHAR) {
                charColumns.add(metadata.getColumnLabel(i).toUpperCase());
                isCharColumn[i - 1] = true;
            }/*from w w w. j  av a 2s  .  c  o m*/
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("CHAR columns: " + charColumns);
        }
    }
}

From source file:DatabaseTest.java

public void setQuery(String q) {
    cache = new Vector();
    try {/*from  www . j  a  v  a 2  s. 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();
    }
}