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:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java

private Record processRow(ResultSet resultSet, long rowCount) throws SQLException, StageException {
    Source.Context context = getContext();
    ResultSetMetaData md = resultSet.getMetaData();
    int numColumns = md.getColumnCount();

    LinkedHashMap<String, Field> fields = jdbcUtil.resultSetToFields(resultSet, commonSourceConfigBean,
            errorRecordHandler, unknownTypeAction, null);

    if (fields.size() != numColumns) {
        errorRecordHandler.onError(JdbcErrors.JDBC_35, fields.size(), numColumns);
        return null; // Don't output this record.
    }/*from   w  w w  .ja v a 2 s. co m*/

    final String recordContext = StringUtils.substring(query.replaceAll("[\n\r]", ""), 0, 100) + "::rowCount:"
            + rowCount + (StringUtils.isEmpty(offsetColumn) ? "" : ":" + resultSet.getString(offsetColumn));
    Record record = context.createRecord(recordContext);
    if (jdbcRecordType == JdbcRecordType.LIST_MAP) {
        record.set(Field.createListMap(fields));
    } else if (jdbcRecordType == JdbcRecordType.MAP) {
        record.set(Field.create(fields));
    } else {
        // type is LIST
        List<Field> row = new ArrayList<>();
        for (Map.Entry<String, Field> fieldInfo : fields.entrySet()) {
            Map<String, Field> cell = new HashMap<>();
            cell.put("header", Field.create(fieldInfo.getKey()));
            cell.put("value", fieldInfo.getValue());
            row.add(Field.create(cell));
        }
        record.set(Field.create(row));
    }
    if (createJDBCNsHeaders) {
        jdbcUtil.setColumnSpecificHeaders(record, Collections.<String>emptySet(), md, jdbcNsHeaderPrefix);
    }
    // We will add cdc operation type to record header even if createJDBCNsHeaders is false
    // we currently support CDC on only MS SQL.
    if (hikariConfigBean.getConnectionString().startsWith("jdbc:sqlserver")) {
        MSOperationCode.addOperationCodeToRecordHeader(record);
    }

    return record;
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Cache the column name and its index./* w ww .ja v a2 s .c  om*/
 *
 * @param resultSetMetaData
 * @throws SQLException
 */
private void cacheMetadata(ResultSetMetaData resultSetMetaData) throws SQLException {
    cachedColumnNames = new HashMap<String, Integer>();
    for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
        final String fieldTypeName = resultSetMetaData.getColumnTypeName(i);
        if (!fieldTypeName.equalsIgnoreCase("geometry")
                && isSupportedPropertyType(resultSetMetaData.getColumnType(i), fieldTypeName)) {
            cachedColumnNames.put(resultSetMetaData.getColumnName(i).toUpperCase(), i);
            columnCountProperties++;
        }
    }
}

From source file:cn.labthink.ReadAccess060.java

private void generateCellData(Integer testID, int cellno) throws SQLException {
    Vector columns = null;/*from  w  w  w  . j av  a  2 s . c  o m*/
    Vector data = null;

    data = new Vector();
    columns = new Vector();

    //                PreparedStatement st = con.prepareStatement("SELECT * FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    PreparedStatement st = conn.prepareStatement(
            "SELECT TESTTEMPERATURE,HUMIDITY,WEIGHT,AMBTEMP,PRODUCETIME,AREA,THICKNESS  FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    st.setInt(1, testID);
    st.setObject(2, cellno);

    rs = st.executeQuery();

    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();
    //store column names 
    for (int i = 1; i <= columnCount; i++) {
        columns.add(md.getColumnName(i));
        //                System.out.println(md.getColumnName(i));
    }
    columns.ensureCapacity(columnCount);

    Vector row;
    while (rs.next()) {

        row = new Vector(columnCount);
        for (int i = 1; i <= columnCount; i++) {
            row.add(rs.getString(i));
            //                    System.out.print(rs.getString(i));
            //                    System.out.print(",");
        }
        //                System.out.print("\r\n");
        data.add(row);

        //Debugging    
    }

    outputexcelCell(columns, data, cellno);
}

From source file:cn.labthink.ReadAccess330.java

private void generateCellData(Integer testID, int cellno) throws SQLException {
    Vector columns = null;/*  w  w w.j a  va 2  s .  c  om*/
    Vector data = null;

    data = new Vector();
    columns = new Vector();

    //                PreparedStatement st = con.prepareStatement("SELECT * FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    PreparedStatement st = conn.prepareStatement(
            "SELECT TIMESPAN,TESTTEMPERATURE,ABOVEHUMIDITY,BELOWHUMIDITY,ABOVEPRESSURE,BELOWPRESSURE,FLOWRATE,OPPM,WPPM,OTR,WVTR,SENSORTEMP,AMBTEMP,TESTTYPE,AMTEMPERATURE,AMHUMIDITY,PRODUCETIME,COFFICIENT  FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    st.setInt(1, testID);
    st.setObject(2, cellno);

    rs = st.executeQuery();

    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();
    //store column names 
    for (int i = 1; i <= columnCount; i++) {
        columns.add(md.getColumnName(i));
        //                System.out.println(md.getColumnName(i));
    }
    columns.ensureCapacity(columnCount);

    Vector row;
    while (rs.next()) {

        row = new Vector(columnCount);
        for (int i = 1; i <= columnCount; i++) {
            row.add(rs.getString(i));
            //                    System.out.print(rs.getString(i));
            //                    System.out.print(",");
        }
        //                System.out.print("\r\n");
        data.add(row);

        //Debugging    
    }

    outputexcelCell(columns, data, cellno);
}

From source file:WeblogicDbServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    String sql = "select * from athlete";
    Connection conn = null;/*ww w .j av a  2 s. c  om*/
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsm = null;

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Weblogic Database Access</title></head><body>");
    out.println("<h2>Database info</h2>");
    out.println("<table border='1'><tr>");

    try {

        conn = pool.getConnection();
        stmt = conn.createStatement();

        rs = stmt.executeQuery(sql);
        rsm = rs.getMetaData();
        int colCount = rsm.getColumnCount();

        //print column names
        for (int i = 1; i <= colCount; ++i) {

            out.println("<th>" + rsm.getColumnName(i) + "</th>");
        }

        out.println("</tr>");

        while (rs.next()) {

            out.println("<tr>");

            for (int i = 1; i <= colCount; ++i)
                out.println("<td>" + rs.getString(i) + "</td>");

            out.println("</tr>");
        }

    } catch (Exception e) {

        throw new ServletException(e.getMessage());

    } finally {

        try {

            stmt.close();
            conn.close();

        } catch (SQLException sqle) {
        }

    }
    out.println("</table></body></html>");
    out.close();

}

From source file:com.bitnine.tadpole.graph.core.editor.extension.browserHandler.CypherFunctionService.java

/**
 * RurukiEye.js ?? ?   .//from   w w w.  j av  a  2s  . c o  m
 * 
 * @param nodeJsonString
 * @return
 */
protected String loadData(final String nodeJsonString) {
    ResultSet rs = null;
    java.sql.Connection javaConn = null;
    Statement statement = null;

    JsonObject jsonNode = JsonObject.readFrom(nodeJsonString);
    RunkiEyeGraph graph = new RunkiEyeGraph();

    try {

        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);

        String reqQuery = "match (n)-[r]->(p) where id(n) = '" + jsonNode.get("id").asString()
                + "' return n, r, p UNION match (n)-[r]->(p) where id(p) = '" + jsonNode.get("id").asString()
                + "' return n, r, p";
        if (logger.isDebugEnabled())
            logger.debug("Execute Math CQL : " + reqQuery);

        javaConn = client.getDataSource().getConnection();
        statement = javaConn.createStatement();

        rs = statement.executeQuery(reqQuery);
        ResultSetMetaData rsmt = rs.getMetaData();

        RurukiNode node = null;
        RurukiEdge rurukiEdge = null;
        Path path = null;

        while (rs.next()) {
            for (int columnIndex = 1; columnIndex <= rsmt.getColumnCount(); columnIndex++) {

                Object obj = rs.getObject(columnIndex);
                if (obj instanceof Vertex) {
                    node = new RurukiNode();
                    Vertex vertex = (Vertex) obj;
                    node.setId(vertex.getVertexId().getOid() + "." + vertex.getVertexId().getId());
                    node.setLabel(vertex.getLabel());
                    node.setProperties(vertex.getProperty().toMap());
                    node.setMetadata(new Metadata(0, 0, vertex));
                    graph.addVertex(node);
                } else if (obj instanceof Edge) {
                    rurukiEdge = new RurukiEdge();
                    Edge relation = (Edge) obj;
                    rurukiEdge.setId(relation.getEdgeId().getOid() + "." + relation.getEdgeId().getId());
                    rurukiEdge.setLabel(relation.getLabel());
                    rurukiEdge.setHeadId(
                            relation.getStartVertexId().getOid() + "." + relation.getStartVertexId().getId());
                    rurukiEdge.setTailId(
                            relation.getEndVertexid().getOid() + "." + relation.getEndVertexid().getId());
                    rurukiEdge.setProperties(relation.getProperty().toMap());
                    graph.addEdge(rurukiEdge);
                } else if (obj instanceof Path) {

                    path = (Path) obj;

                    for (Edge relation : path.edges()) {

                        rurukiEdge = new RurukiEdge();

                        rurukiEdge.setId(relation.getEdgeId().getOid() + "." + relation.getEdgeId().getId());
                        rurukiEdge.setLabel(relation.getLabel());
                        rurukiEdge.setHeadId(relation.getStartVertexId().getOid() + "."
                                + relation.getStartVertexId().getId());
                        rurukiEdge.setTailId(
                                relation.getEndVertexid().getOid() + "." + relation.getEndVertexid().getId());
                        rurukiEdge.setProperties(relation.getProperty().toMap());

                        graph.addEdge(rurukiEdge);

                    }

                    if (logger.isDebugEnabled())
                        logger.debug("path start " + path.start());
                    if (logger.isDebugEnabled())
                        logger.debug("path length " + String.valueOf(path.length()));
                    for (Vertex vertex : path.vertexs()) {
                        node = new RurukiNode();
                        node.setId(vertex.getVertexId().getOid() + "." + vertex.getVertexId().getId());
                        node.setLabel(vertex.getLabel());
                        node.setProperties(vertex.getProperty().toMap());
                        node.setMetadata(new Metadata(0, 0, vertex));

                        graph.addVertex(node);
                    }
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Unknow Class " + obj.getClass().toString());
                }
            }
        }

        graph.calcInOutEdgeCount();

    } catch (Exception e) {
        logger.error(e);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
        }
        try {
            if (javaConn != null)
                javaConn.close();
        } catch (Exception e) {
        }

    }
    return graph.toJSONString();
}

From source file:com.ws.WS_TCS201.java

@Path("/GetTCD")
@JSONP(queryParam = "callback")
@GET//from  w  ww.j a  v a  2 s .  co m
@Produces({ "application/x-javascript" })
public String GetTCD(@QueryParam("callback") String callback) {

    JSONObject obj1 = new JSONObject();
    LinkedList l1 = new LinkedList();
    //JSONArray l1 = new JSONArray();

    PreparedStatement prepStmt = null;

    try {
        String cSQL = "SELECT tcctcd,CONCAT(tcctcd,\" - \",trim(tcctxt)) AS name FROM TCSTCC "
                + "WHERE tcctcd NOT IN (\"A\",\"L\",\"N\",\"J\",\"R\",\"E\") " + "ORDER BY tcctcd ";
        prepStmt = connection.prepareStatement(cSQL);
        ResultSet result = prepStmt.executeQuery();
        ResultSetMetaData rsmd = result.getMetaData();
        int numcols = rsmd.getColumnCount();

        while (result.next()) {
            LinkedHashMap m1 = new LinkedHashMap();
            for (int j = 1; j <= numcols; j++) {
                Object obj = result.getObject(j);
                m1.put(rsmd.getColumnName(j).toString(), obj.toString());
            }
            l1.add(m1);
        }
        obj1.put("record", l1);
    } catch (SQLException e) {
        prepStmt = null;
        e.printStackTrace();
    } catch (Exception e) {
        prepStmt = null;
        e.printStackTrace();
    }
    return obj1.toString();
}

From source file:herddb.cli.HerdDBCLI.java

private static ExecuteStatementResult reallyExecuteStatement(final Statement statement, boolean resultSet,
        boolean verbose, boolean getResults, boolean prettyPrint) throws SQLException {

    if (resultSet) {
        try (ResultSet rs = statement.getResultSet()) {
            List<Map<String, Object>> results = new ArrayList<>();
            TextTableBuilder tb = new TextTableBuilder();

            ResultSetMetaData md = rs.getMetaData();
            List<String> columns = new ArrayList<>();
            int ccount = md.getColumnCount();
            for (int i = 1; i <= ccount; i++) {
                columns.add(md.getColumnName(i));
            }/*from   w w  w . ja  va  2  s.c o m*/

            if (!getResults) {
                if (prettyPrint) {
                    tb.addIntestation(columns);
                } else {
                    System.out.println(columns.stream().collect(Collectors.joining(";")));
                }
            }

            while (rs.next()) {
                List<String> values = new ArrayList<>();
                for (int i = 1; i <= ccount; i++) {
                    String value = rs.getString(i);
                    if (value == null) {
                        value = "<NULL>";
                    }
                    values.add(value);
                }

                if (getResults) {
                    Map<String, Object> row = new LinkedHashMap<>(); // Preserving order
                    int i = 0;
                    for (String col : columns) {
                        row.put(col, values.get(i++));
                    }
                    results.add(row);
                } else {
                    if (prettyPrint) {
                        tb.addRow(values);
                    } else {
                        System.out.println(values.stream().collect(Collectors.joining(";")));
                    }
                }
            }

            if (getResults) {
                return new ExecuteStatementResult(results);
            }
            if (prettyPrint) {
                System.out.println("\n" + tb.toString());
            }
            return null;
        }
    } else {
        int updateCount = statement.getUpdateCount();
        if (verbose) {
            System.out.println("UPDATE COUNT: " + updateCount);
        }
        return new ExecuteStatementResult(updateCount >= 0 ? updateCount : 0);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.images.CollectionDataFetcher.java

/**
 * @param rs/*from   w  w w .java  2s.  c  o  m*/
 * @param tableId
 * @return
 * @throws SQLException 
 */
private List<Triple<String, String, Object>> readDataIntoMap(final ResultSet rs, final int tableId)
        throws SQLException {
    List<BubbleDisplayInfo> displayInfos = bciHash.get(tableId);
    List<Triple<String, String, Object>> dataList = new ArrayList<Triple<String, String, Object>>();
    if (rs != null) {
        if (rs.next()) {
            ResultSetMetaData rsmd = rs.getMetaData();

            for (int i = 1; i < rsmd.getColumnCount(); i++) {
                BubbleDisplayInfo bdi = displayInfos.get(i - 1);
                Object val = rs.getObject(i);

                if (bdi.getColTblId() == Attachment.getClassTableId()
                        && bdi.getColumnName().equals("OrigFilename")) {
                    val = FilenameUtils.getName(val.toString());
                }

                if (bdi.getFormatter() != null) {
                    val = bdi.getFormatter().formatToUI(val);

                } else if (val instanceof Calendar) {
                    val = scrDateFormat.format((Calendar) val);

                } else if (val instanceof Date) {
                    val = scrDateFormat.format((Date) val);

                } else if (val instanceof BigDecimal) {
                    val = StringUtils.stripEnd(val.toString(), "0");

                } else if (bdi.getFieldInfo().getPickListName() != null) {
                    PickListIFace pl = PickListDBAdapterFactory.getInstance()
                            .getPickList(bdi.getFieldInfo().getPickListName());
                    if (pl != null) {
                        for (PickListItemIFace pli : pl.getItems()) {
                            if (pli.getValue() != null && pli.getValue().equals(val)) {
                                val = pli.getTitle();
                                break;
                            }
                        }
                    }
                }
                String title = getColumnTitle(bdi, tableId) + ": ";
                dataList.add(new Triple<String, String, Object>(bdi.getFieldInfo().getColumn(), title, val));
            }
            //System.out.println(rs.getObject(rsmd.getColumnCount()));
            dataList.add(new Triple<String, String, Object>("Id", "Id", rs.getObject(rsmd.getColumnCount())));
        }
        rs.close();
    }
    return dataList;
}

From source file:CSVWriter.java

protected void writeColumnNames(ResultSetMetaData metadata)
  throws SQLException {
      /*from  w w w . ja  v  a2 s.  c  o m*/
  int columnCount =  metadata.getColumnCount();
      
  String[] nextLine = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
  nextLine[i] = metadata.getColumnName(i + 1);
}
  writeNext(nextLine);
}