Example usage for java.sql ResultSet absolute

List of usage examples for java.sql ResultSet absolute

Introduction

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

Prototype

boolean absolute(int row) throws SQLException;

Source Link

Document

Moves the cursor to the given row number in this ResultSet object.

Usage

From source file:architecture.ee.jdbc.util.impl.JdbcHelperImpl.java

public void scrollResultSet(ResultSet rs, int rowNumber) throws SQLException {
    if (isScrollResultsSupported()) {
        if (rowNumber > 0) {
            rs.setFetchDirection(1000);/* w w w . j av a2 s.com*/
            rs.absolute(rowNumber);
        }
    } else {
        for (int i = 0; i < rowNumber; i++)
            rs.next();
    }
}

From source file:com.predic8.membrane.core.interceptor.statistics.StatisticsProvider.java

private void createJson(Exchange exc, ResultSet r, int offset, int max, int total)
        throws IOException, JsonGenerationException, SQLException {

    StringWriter jsonTxt = new StringWriter();

    JsonGenerator jsonGen = jsonFactory.createGenerator(jsonTxt);
    jsonGen.writeStartObject();//from   ww w .j av a2s.c o  m
    jsonGen.writeArrayFieldStart("statistics");
    int size = 0;
    r.absolute(offset + 1); //jdbc doesn't support paginating. This can be inefficient.
    while (size < max && !r.isAfterLast()) {
        size++;
        writeRecord(r, jsonGen);
        r.next();
    }
    jsonGen.writeEndArray();
    jsonGen.writeNumberField("total", total);
    jsonGen.writeEndObject();
    jsonGen.flush();

    createResponse(exc, jsonTxt);
}

From source file:BQJDBC.QueryResultTest.QueryResultTest.java

@Test
public void QueryResultTest12() {
    int limitNum = 40000;
    final String sql = "SELECT weight_pounds  FROM publicdata:samples.natality LIMIT " + limitNum;

    this.logger.info("Test number: 12");
    this.logger.info("Running query:" + sql);

    java.sql.ResultSet Result = null;
    try {//from  w  w w. j ava2  s . c om
        Statement stm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        stm.setFetchSize(1000);
        Result = stm.executeQuery(sql);
    } catch (SQLException e) {
        this.logger.error("SQLexception" + e.toString());
        Assert.fail("SQLException" + e.toString());
    }
    Assert.assertNotNull(Result);
    try {/*
         int j = 0;
         for (int i = 0; i < limitNum-1; i++) {
         if(i%1000 == 0) {
             logger.debug("fetched 1k for the " + ++j + ". time");
         }
         Assert.assertTrue(Result.next());  
         }*/
        Result.absolute(limitNum);
        Assert.assertTrue(true);
    } catch (SQLException e) {
        e.printStackTrace();
        Assert.fail();
    }
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testAbsolute() throws SQLException {
    stat = conn.createStatement();// w  w  w  . j a  va 2  s  .c  om
    stat.execute("CREATE TABLE test(ID INT PRIMARY KEY)");
    // there was a problem when more than MAX_MEMORY_ROWS where in the result
    // set
    stat.execute("INSERT INTO test SELECT X FROM SYSTEM_RANGE(1, 200)");
    Statement s2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = s2.executeQuery("SELECT * FROM test ORDER BY ID");
    for (int i = 100; i > 0; i--) {
        rs.absolute(i);
        assertEquals(i, rs.getInt(1));
    }
    stat.execute("DROP TABLE test");
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

private void handleResults(StatementScope statementScope, ResultSet rs, int skipResults, int maxResults,
        RowHandlerCallback callback) throws SQLException {
    try {//  w  w  w  .  j ava  2  s  .co  m
        statementScope.setResultSet(rs);
        ResultMap resultMap = statementScope.getResultMap();
        if (resultMap != null) {
            // Skip Results
            if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
                if (skipResults > 0) {
                    rs.absolute(skipResults);
                }
            } else {
                for (int i = 0; i < skipResults; i++) {
                    if (!rs.next()) {
                        return;
                    }
                }
            }

            // Get Results
            int resultsFetched = 0;
            while ((maxResults == SqlExecutor.NO_MAXIMUM_RESULTS || resultsFetched < maxResults) && rs.next()) {
                Object[] columnValues = resultMap.resolveSubMap(statementScope, rs).getResults(statementScope,
                        rs);
                callback.handleResultObject(statementScope, columnValues, rs);
                resultsFetched++;
            }
        }
    } finally {
        statementScope.setResultSet(null);
    }
}

From source file:GuestBookServlet.java

private void printComments(PrintWriter out, Locale loc) throws IOException {
    Connection conn = null;/* ww w. ja v a  2 s.c  o  m*/

    try {
        DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, loc);
        ResultSet results;
        Statement stmt;
        int rows, count;

        conn = DriverManager.getConnection(jdbcURL, connectionProperties);
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        results = stmt.executeQuery("SELECT NAME, EMAIL, CMT_DATE, " + "COMMENT, COMMENT_ID " + "FROM COMMENT "
                + "ORDER BY CMT_DATE");
        out.println("<dl>");
        results.last();
        results.next();
        rows = results.getRow();
        // pick a random row
        rows = random.nextInt() % rows;
        if (rows < 4) {
            // if the random row is less than 4, print the first 4 rows
            results.afterLast();
        } else {
            // otherwise go to the specified row, print the prior 5 rows
            results.absolute(rows);
        }
        count = 0;
        // print up to 5 rows going backwards from the randomly
        // selected row
        while (results.previous() && (count < 5)) {
            String name, email, cmt;
            Date date;

            count++;
            name = results.getString(1);
            if (results.wasNull()) {
                name = "Unknown User";
            }
            email = results.getString(2);
            if (results.wasNull()) {
                email = "user@host";
            }
            date = results.getDate(3);
            if (results.wasNull()) {
                date = new Date((new java.util.Date()).getTime());
            }
            cmt = results.getString(4);
            if (results.wasNull()) {
                cmt = "No comment.";
            }
            out.println("<dt><b>" + name + "</b> (" + email + ") on " + fmt.format(date) + "</dt>");
            cmt = noXML(cmt);
            out.println("<dd> " + cmt + "</dd>");
        }
        out.println("</dl>");
    } catch (SQLException e) {
        out.println("A database error occurred: " + e.getMessage());
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:com.glaf.core.jdbc.QueryHelper.java

protected void skipRows(ResultSet rs, int firstResult, int maxResults) throws SQLException {
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
        if (firstResult != 0) {
            rs.absolute(firstResult);
        }/*from  w  ww . jav a 2s  . c  o  m*/
    } else {
        for (int i = 0; i < firstResult; i++) {
            rs.next();
        }
    }
}

From source file:com.glaf.core.jdbc.QueryHelper.java

protected void skipRows(ResultSet rs, int start) throws SQLException {
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
        if (start != 0) {
            logger.debug("rs absolute " + start);
            rs.absolute(start);
        }// www  . j a v a 2s. c  o  m
    } else {
        for (int i = 0; i < start; i++) {
            rs.next();
        }
    }
}

From source file:net.mlw.vlh.adapter.jdbc.AbstractJdbcAdapter.java

/**
 * @see net.mlw.vlh.ValueListAdapter#getValueList(java.lang.String,
 *      net.mlw.vlh.ValueListInfo)//from www.j a va2  s . co m
 */
public ValueList getValueList(String name, ValueListInfo info) {
    if (info.getSortingColumn() == null) {
        info.setPrimarySortColumn(getDefaultSortColumn());
        info.setPrimarySortDirection(getDefaultSortDirectionInteger());
    }

    int numberPerPage = info.getPagingNumberPer();

    if (numberPerPage == Integer.MAX_VALUE) {
        numberPerPage = getDefaultNumberPerPage();
        info.setPagingNumberPer(numberPerPage);
    }

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;

    try {
        boolean doSqlPaging = ((getAdapterType() & DO_PAGE) == 0);

        connection = connectionCreator.createConnection();

        StringBuffer query = (sqlPagingSupport != null) ? sqlPagingSupport.getPagedQuery(sql)
                : new StringBuffer(sql);
        statement = statementBuilder.generate(connection, query, info.getFilters(),
                sqlPagingSupport == null && doSqlPaging);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(query.toString());
        }
        if (showSql) {
            System.out.println("sql: " + query.toString());
        }
        result = getResultSet(statement, info);

        if (sqlPagingSupport != null) {
            PreparedStatement countStatement = null;
            ResultSet countResult = null;

            try {
                StringBuffer countQuery = sqlPagingSupport.getCountQuery(sql);
                countStatement = statementBuilder.generate(connection, countQuery, info.getFilters(), false);
                if (showSql) {
                    System.out.println("count sql: " + countQuery.toString());
                }

                countResult = countStatement.executeQuery();
                if (countResult.next()) {
                    info.setTotalNumberOfEntries(countResult.getInt(1));
                }
            } finally {
                JdbcUtil.close(countResult, countStatement, null);
            }

        } else if (doSqlPaging) {
            result.last();
            int totalRows = result.getRow();
            info.setTotalNumberOfEntries(totalRows);

            if (numberPerPage == 0) {
                numberPerPage = getDefaultNumberPerPage();
            }

            int pageNumber = info.getPagingPage();
            if (pageNumber > 1) {
                if ((pageNumber - 1) * numberPerPage > totalRows) {
                    pageNumber = ((totalRows - 1) / numberPerPage) + 1;
                    info.setPagingPage(pageNumber);
                }
            }

            if (pageNumber > 1) {
                result.absolute((pageNumber - 1) * numberPerPage);
            } else {
                result.beforeFirst();
            }
        }

        List list = processResultSet(name, result, (doSqlPaging) ? numberPerPage : Integer.MAX_VALUE, info);

        if (!doSqlPaging) {
            info.setTotalNumberOfEntries(list.size());
        }

        return new DefaultListBackedValueList(list, info);

    } catch (Exception e) {
        LOGGER.error(e);
        throw new RuntimeException(e);
    } finally {
        connectionCreator.close(result, statement, connection);
    }
}