Example usage for java.sql ResultSet isFirst

List of usage examples for java.sql ResultSet isFirst

Introduction

In this page you can find the example usage for java.sql ResultSet isFirst.

Prototype

boolean isFirst() throws SQLException;

Source Link

Document

Retrieves whether the cursor is on the first row of this ResultSet object.

Usage

From source file:unikn.dbis.univis.visualization.graph.VGraph.java

/**
 * @param result The given resultset from the sql action.
 * @throws SQLException// w ww  . ja  v  a 2 s.c  om
 */
public void fillChartData(VDimension dimension, ResultSet result, ResultSet testResult) throws SQLException {

    layout.setAlignment(SwingConstants.CENTER);

    ResultSetMetaData data = result.getMetaData();
    int idPos = data.getColumnCount();
    int namePos = idPos - 1;
    int bufferPos = namePos - 1;

    List<String> testList = new ArrayList<String>();

    while (testResult.next()) {
        testList.add(testResult.getString(1));
    }

    List<String> helpList = new ArrayList<String>(testList);

    if (root == null) {

        cellHistory.historize();

        if (ChartType.BAR_CHART_VERTICAL.equals(chartType) || ChartType.BAR_CHART_HORIZONTAL.equals(chartType)
                || ChartType.AREA_CHART.equals(chartType)) {
            dataset = new DefaultCategoryDataset();

            while (result.next()) {
                ((DefaultCategoryDataset) dataset).addValue(result.getInt(1), result.getString(namePos + 1),
                        "");
            }
        } else {
            dataset = new DefaultPieDataset();

            while (result.next()) {
                ((DefaultPieDataset) dataset).setValue(result.getString(namePos + 1), result.getInt(1));
            }
        }

        root = createVertex(rootHeadLine, "");
        root.setCellId("root");
        cache.insert(root);
        cellHistory.add(root);
    } else {
        cellHistory.historize();

        String buffer = "";
        if (ChartType.BAR_CHART_VERTICAL.equals(chartType) || ChartType.BAR_CHART_HORIZONTAL.equals(chartType)
                || ChartType.AREA_CHART.equals(chartType)) {
            while (result.next()) {

                String currentValue = result.getString(idPos);

                if (!buffer.equals(currentValue)) {

                    if (!result.isFirst()) {
                        if (!helpList.isEmpty()) {
                            for (String missing : helpList) {
                                ((DefaultCategoryDataset) dataset).addValue(0, missing, "");
                            }
                        }
                    }

                    dataset = new DefaultCategoryDataset();
                    VGraphCell nextCell = createVertex(
                            MessageResolver.getMessage("data_reference." + dimension.getI18nKey()) + " ("
                                    + result.getString(bufferPos) + ")",
                            result.getString(idPos));
                    createEdges(nextCell, result.getString(idPos));
                    cache.insert(nextCell);
                    cellHistory.add(nextCell);
                    helpList = new ArrayList<String>(testList);
                }

                for (String available : testList) {
                    if (result.getString(namePos).equals(available)) {
                        helpList.remove(available);
                    }
                }

                ((DefaultCategoryDataset) dataset).addValue(result.getInt(1), result.getString(namePos), "");
                buffer = currentValue;

                if (result.isLast()) {
                    if (!helpList.isEmpty()) {
                        for (String missing : helpList) {
                            ((DefaultCategoryDataset) dataset).addValue(0, missing, "");
                        }
                    }
                }
            }

        } else {
            while (result.next()) {

                String currentValue = result.getString(idPos);

                LOG.info(result.getString(2));

                if (!buffer.equals(currentValue)) {

                    dataset = new DefaultPieDataset();

                    VGraphCell nextCell = createVertex(
                            MessageResolver.getMessage("data_reference." + dimension.getI18nKey()) + " ("
                                    + result.getString(bufferPos) + ")",
                            result.getString(idPos));
                    createEdges(nextCell, result.getString(idPos));
                    cache.insert(nextCell);
                    cellHistory.add(nextCell);
                }

                ((DefaultPieDataset) dataset).setValue(result.getString(namePos), result.getInt(1));

                buffer = currentValue;
            }
        }
    }
    layout.run(facade);
    facade.setOrdered(true);
    Map nested = facade.createNestedMap(true, true);
    cache.edit(nested);
}

From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java

/**
 * Produce a JDOM Element for an instance of Results object.
 * <br>/*from  w  ww.  j a  va 2s .co m*/
 * @param object for which the JDOM Element is to be produced.
 * @param beginRow The starting row from which the results are to be converted to XML.
 * @param endRow The row until which the results are to be converted to XML.
 * @return the JDOM element of the results object that was converted to XML.
 * @exception JDOMException if there is an error producing XML.
 * @exception SQLException if there is an error walking through the ResultSet object.
 */
private Element produceResults(ResultSet object, int beginRow, int endRow) throws JDOMException, SQLException {

    if (object.isClosed()) {
        throw new SQLException("ResultSet is closed at this point, unable to product results"); //$NON-NLS-1$

    }

    if (beginRow < START_ROW) {
        throw new IllegalArgumentException("The starting row cannot be less than 1."); //$NON-NLS-1$
    } else if (beginRow > endRow) {
        throw new IllegalArgumentException("The starting row cannot be less than the ending row."); //$NON-NLS-1$
    }

    int currentRow = object.getRow() + 1;

    if (beginRow > currentRow) {
        while (!object.isLast() && currentRow != beginRow) {
            object.next();
            currentRow++;
        }

    } else if (beginRow < currentRow) {
        while (!object.isFirst() && currentRow != beginRow) {
            object.previous();
            currentRow--;
        }
    }

    return produceMsg(object, endRow);
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@SuppressWarnings("deprecation")
@Test//from  w  ww.  java  2 s  . com
public void testResultSetWhenClosed() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);

    rs.close();

    try {
        rs.isBeforeFirst();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.isAfterLast();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.isFirst();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.isLast();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.beforeFirst();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.afterLast();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.first();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.last();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.next();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getRow();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getType();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getConcurrency();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.rowUpdated();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.rowDeleted();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.rowInserted();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getStatement();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.wasNull();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getString(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getString("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getShort(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getShort("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(1, null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(1, null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(1, null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getUnicodeStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getUnicodeStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getMetaData();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.setFetchDirection(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFetchDirection();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.setFetchSize(100);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFetchSize();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getHoldability();
        fail();
    } catch (SQLException ignore) {
    }

    statement.close();
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

private int printResultSet(final ResultSet rs) throws Exception {
    int count = 0;
    long empno, empno2;
    String ename, ename2;/*from  w ww.  ja va  2s  .c om*/
    String[] nicknames;
    String[] nicknames2;
    double salary, salary2;
    Date hireDate, hireDate2;

    System.out.println();
    System.out.println("===================================================================");
    System.out.println("   empno        ename      salary       hire_date       nicknames");
    System.out.println("===================================================================");

    while (rs.next()) {
        ++count;

        if (count == 1) {
            assertTrue(rs.isFirst());
        } else {
            assertFalse(rs.isFirst());
        }

        assertEquals(count, rs.getRow());

        empno = rs.getLong(1);
        assertFalse(rs.wasNull());
        empno2 = rs.getLong("empno");
        assertEquals(empno, empno2);
        ename = rs.getString(2);
        ename2 = rs.getString("ename");
        assertEquals(ename, ename2);
        salary = rs.getDouble(3);
        salary2 = rs.getDouble("salary");
        assertEquals(salary, salary2, 0.001);
        hireDate = rs.getDate(4);
        hireDate2 = rs.getDate("hiredate");
        assertEquals(hireDate, hireDate2);
        nicknames = (String[]) rs.getArray(5).getArray();
        nicknames2 = (String[]) rs.getArray("nicknames").getArray();
        assertArrayEquals(nicknames, nicknames2);

        String nodeName = rs.getString(Constants.COLUMN_JCR_NAME);
        assertEquals("testdata-" + count, nodeName);
        assertEquals("/testdatafolder/" + nodeName, rs.getString(Constants.COLUMN_JCR_PATH));
        String nodeId = rs.getString(Constants.COLUMN_JCR_UUID);
        assertTrue(nodeId != null && !nodeId.isEmpty());
        assertTrue(rs.getDouble(Constants.COLUMN_JCR_SCORE) > 0.0);

        assertWrongValueFormatColumn(rs);
        assertNonExistingColumn(rs);

        System.out.println(String.format(REC_OUT_FORMAT, empno, ename, salary,
                new SimpleDateFormat("yyyy-MM-dd").format(hireDate), join(nicknames, ",")));
        System.out.println(String.format(NODE_INFO_OUT_FORMAT, rs.getString("jcr:uuid"),
                rs.getString("jcr:name"), rs.getString("jcr:path"), rs.getDouble("jcr:score")));

        assertEquals(count, empno);
        assertEquals("Name' " + count, ename);
        assertEquals(100000.0 + count, salary, .1);
        assertEquals(getEmpHireDate().getTimeInMillis(), hireDate.getTime());

        assertFalse(rs.rowUpdated());
        assertFalse(rs.rowInserted());
        assertFalse(rs.rowDeleted());
    }

    System.out.println("==================================================");
    System.out.println();

    return count;
}

From source file:ProcessRequest.java

public void parseQueryResults(ResultSet rs, String table, OutputStream os, boolean append)
        throws SQLException, JSONException, IOException {
    //JSONArray resultJSONArray = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    rs.last();// www  .j a v a2  s  .  c  om
    int rows = rs.getRow();
    os.write(new String("total rows: " + rows).getBytes());
    rs.first();
    int rowCount = 0;
    while (rs.next()) {
        if (!rs.isFirst() || append) {
            os.write(new String(",\n").getBytes());
            os.write(new String("" + rowCount).getBytes());
        }
        if (rowCount >= 69)
            System.out.println("break point");
        rowCount++;
        JSONObject result = new JSONObject();
        JSONObject resultMeta = new JSONObject();
        resultMeta.put("table", table);
        result.put("metadata", resultMeta);
        for (int i = 1; i <= columns; i++) {
            //out.println("<td>"+rs.getString(i)+"</td>");
            int type = rsmd.getColumnType(i);
            //result.put(rsmd.getColumnName(i), rs.get)
            switch (type) {
            case Types.BIT:
                result.put(rsmd.getColumnName(i), rs.getBoolean(i));
                break;
            case Types.TINYINT:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.SMALLINT:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.INTEGER:
                //System.out.println(rsmd.getColumnName(i) + "  type: "+type);
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.BIGINT:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.FLOAT:
                result.put(rsmd.getColumnName(i), rs.getFloat(i));
                break;
            case Types.REAL:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.DOUBLE:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.NUMERIC:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.DECIMAL:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.CHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.VARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.LONGVARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.DATE: {
                java.util.Date date = rs.getDate(i);
                result.put(rsmd.getColumnName(i), date.getTime());
                break;
            }
            case Types.TIME: {
                java.util.Date date = rs.getDate(i);
                result.put(rsmd.getColumnName(i), date.getTime());
                break;
            }
            case Types.TIMESTAMP: {
                java.util.Date date = rs.getDate(i);
                result.put(rsmd.getColumnName(i), date.getTime());
                break;
            }
            case Types.BINARY:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.VARBINARY:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.LONGVARBINARY:
                result.put(rsmd.getColumnName(i), rs.getLong(i));
                break;
            case Types.NULL:
                result.put(rsmd.getColumnName(i), "");
                break;
            case Types.BOOLEAN:
                result.put(rsmd.getColumnName(i), rs.getBoolean(i));
                break;
            case Types.ROWID:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.NCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.NVARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.LONGNVARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.SQLXML:
            case Types.NCLOB:
            case Types.DATALINK:
            case Types.REF:
            case Types.OTHER:
            case Types.JAVA_OBJECT:
            case Types.DISTINCT:
            case Types.STRUCT:
            case Types.ARRAY:
            case Types.BLOB:
            case Types.CLOB:
            default:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            }
        }
        //if(table.equals("Ticket"))
        //System.out.println(result.toString(5));
        //if(result.getInt("TicketNumber")==126868)
        //   System.out.println("break point");
        //resultJSONArray.put(result);
        os.write(result.toString(5).getBytes());
    }
    //return resultJSONArray;
}

From source file:org.intermine.bio.dataconversion.ModEncodeMetaDataProcessor.java

/**
 * ==========================//from  ww  w  . j a va  2s  . co  m
 *    EXPERIMENTAL FACTORS
 * ==========================
 */
private void processEFactor(Connection connection) throws SQLException, ObjectStoreException {
    long bT = System.currentTimeMillis(); // to monitor time spent in the process

    ResultSet res = getEFactors(connection);
    int count = 0;
    int prevRank = -1;
    int prevSub = -1;
    ExperimentalFactor ef = null;
    String name = null;

    while (res.next()) {
        Integer submissionId = new Integer(res.getInt("experiment_id"));
        if (deletedSubMap.containsKey(submissionId)) {
            continue;
        }

        Integer rank = new Integer(res.getInt("rank"));
        String value = res.getString("value");

        // the data is alternating between EF types and names, in order.
        if (submissionId != prevSub) {
            // except for the first record, this is a new EF object
            if (!res.isFirst()) {
                submissionEFMap.put(prevSub, ef);
                LOG.info("EF MAP: " + dccIdMap.get(prevSub) + "|" + ef.efNames);
                LOG.info("EF MAP types: " + rank + "|" + ef.efTypes);
            }
            ef = new ExperimentalFactor();
        }
        if (rank != prevRank || submissionId != prevSub) {
            // this is a name
            if (getPreferredSynonym(value) != null) {
                value = getPreferredSynonym(value);
            }
            ef.efNames.add(value);
            name = value;
            count++;
        } else {
            // this is a type
            ef.efTypes.put(name, value);
            name = null;
            if (res.isLast()) {
                submissionEFMap.put(submissionId, ef);
                LOG.debug("EF MAP last: " + submissionId + "|" + rank + "|" + ef.efNames);
            }
        }
        prevRank = rank;
        prevSub = submissionId;
    }
    res.close();
    LOG.info("created " + count + " experimental factors");
    LOG.info("PROCESS TIME experimental factors: " + (System.currentTimeMillis() - bT) + " ms");
}

From source file:org.wso2.carbon.appmgt.impl.dao.AppMDAO.java

/**
 * Get app hits when ui data activity data source hasn't set to DAS data source.
 * @param conn Connection./*from   www. j a v  a2 s . c o m*/
 * @param userId user Id.
 * @param startIndex pagination start index.
 * @param pageSize No of elements per page.
 * @param builderDataContext builder with data context.
 * @return a list of UUIDs.
 * @throws AppManagementException
 */
private static List<String> getAppHitStatsFromAppmDBOnly(Connection conn, String userId, int startIndex,
        int pageSize, StringBuilder builderDataContext) throws AppManagementException {
    ResultSet rs = null;
    PreparedStatement ps = null;
    List<String> uuidsList = new ArrayList<String>();
    try {
        String query = "SELECT * FROM (SELECT HIT.UUID ,COUNT(*) AS HIT_COUNT,UPPER(APP_NAME) "
                + "AS APP_NAME, HIT.CONTEXT FROM APM_APP_HITS  HIT " + "WHERE HIT.USER_ID=? GROUP BY HIT.UUID "
                + "UNION ALL "
                + "SELECT UUID ,0 AS HIT_COUNT, UPPER(APP_NAME) AS APP_NAME, CONTEXT FROM APM_APP "
                + "WHERE UUID NOT IN (SELECT UUID FROM APM_APP_HITS  WHERE USER_ID=? )) A "
                + "ORDER BY HIT_COUNT DESC,APP_NAME ASC LIMIT ? , ?";

        if (conn.getMetaData().getDriverName().contains("Oracle")) {
            query = "SELECT * FROM (SELECT HIT.UUID ,COUNT(*) AS HIT_COUNT,UPPER(APP_NAME) "
                    + "AS APP_NAME, HIT.CONTEXT FROM APM_APP_HITS HIT " + "WHERE HIT.USER_ID=? "
                    + "GROUP BY HIT.UUID, HIT.APP_NAME, HIT.VERSION, HIT.CONTEXT UNION ALL "
                    + "SELECT UUID ,0 AS HIT_COUNT, UPPER(APP_NAME) AS APP_NAME, CONTEXT FROM APM_APP "
                    + "WHERE UUID NOT IN (SELECT UUID FROM APM_APP_HITS WHERE USER_ID=? )) A  "
                    + "WHERE ROWNUM >= ? AND ROWNUM <= ? " + "ORDER BY HIT_COUNT DESC,APP_NAME ASC ";
        }

        ps = conn.prepareStatement(query);
        ps.setString(1, userId);
        ps.setString(2, userId);
        ps.setInt(3, startIndex);
        ps.setInt(4, pageSize);
        rs = ps.executeQuery();
        if (rs.isFirst()) {
            uuidsList = new ArrayList<String>();
        }
        while (rs.next()) {
            uuidsList.add(rs.getString("UUID"));
        }
    } catch (SQLException e) {
        throw new AppManagementException(
                "SQL Exception is occurred while fetching the store hit sorted data from "
                        + "App Manager Database: " + builderDataContext.toString() + " : " + e.getMessage(),
                e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return uuidsList;
}