Example usage for java.sql Statement getFetchSize

List of usage examples for java.sql Statement getFetchSize

Introduction

In this page you can find the example usage for java.sql Statement getFetchSize.

Prototype

int getFetchSize() throws SQLException;

Source Link

Document

Retrieves the number of result set rows that is the default fetch size for ResultSet objects generated from this Statement object.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);/*from  w  ww  .  j av  a  2  s  .c  om*/

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    Statement stmt = connection.createStatement();
    int fetchSize = stmt.getFetchSize();

    // Set the fetch size on the statement
    stmt.setFetchSize(100);

    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Change the fetch size on the result set
    resultSet.setFetchSize(100);

}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);//from  w ww.j  a  v a 2s  .c  om

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    // Get the fetch size of a statement
    Statement stmt = connection.createStatement();
    int fetchSize = stmt.getFetchSize();

    // Set the fetch size on the statement
    stmt.setFetchSize(100);

    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Change the fetch size on the result set
    resultSet.setFetchSize(100);

}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);/*from  w  w  w .  j  a  v  a  2  s .  c  om*/

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    // Get the fetch size of a statement
    Statement stmt = connection.createStatement();
    int fetchSize = stmt.getFetchSize();

    // Set the fetch size on the statement
    stmt.setFetchSize(100);

    // Create a result set
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Change the fetch size on the result set
    System.out.println(resultSet.getFetchSize());

}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);// ww w .j  av  a 2  s .c om

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    // Get the fetch size of a statement
    Statement stmt = connection.createStatement();
    int fetchSize = stmt.getFetchSize();

    // Set the fetch size on the statement
    stmt.setFetchSize(100);

    // Create a result set
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Change the fetch size on the result set
    resultSet.setFetchSize(100);

}

From source file:com.taobao.datax.plugins.reader.postgrereader.PostgreReader.java

@Override
public int startRead(LineSender lineSender) {
    DBResultSetSender proxy = DBResultSetSender.newSender(lineSender);
    proxy.setMonitor(getMonitor());//from   w w  w  .j  a  v  a2 s  .  co m
    proxy.setDateFormatMap(genDateFormatMap());

    String sql = param.getValue(ParamKey.sql);
    logger.info(String.format("PostgreReader start to query %s .", sql));
    ResultSet rs = null;
    Connection connection = null;
    try {
        connection = getCon();
        connection.setAutoCommit(false);
        Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        logger.info("set postgre statement fetch size");
        stmt.setFetchSize(fetchSize);
        logger.info("connection info autoCommit:" + connection.getAutoCommit() + " fetchSize"
                + stmt.getFetchSize());
        rs = DBUtils.query(stmt, sql);
        logger.info("get a ResultSet");
        proxy.sendToWriter(rs);
        logger.info("send to writer");
        proxy.flush();
        getMonitor().setStatus(PluginStatus.READ_OVER);
        return PluginStatus.SUCCESS.value();
    } catch (SQLException e) {
        logger.error(ExceptionTracker.trace(e));
        throw new DataExchangeException(e);
    } finally {
        if (null != rs) {
            DBUtils.closeResultSet(rs);
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }

}

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

@Test
public void testStatement() throws SQLException, IOException, InterruptedException {
    Statement stat = conn.createStatement();

    assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability());
    conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
    assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
    // ignored/* w  w  w  . j av a  2 s  .  co  m*/
    stat.setCursorName("x");
    // fixed return value
    assertEquals(stat.getFetchDirection(), ResultSet.FETCH_FORWARD);
    // ignored
    stat.setFetchDirection(ResultSet.FETCH_REVERSE);
    // ignored
    stat.setMaxFieldSize(100);

    assertEquals(conf.getInt(FConstants.WASP_JDBC_FETCHSIZE, FConstants.DEFAULT_WASP_JDBC_FETCHSIZE),
            stat.getFetchSize());
    stat.setFetchSize(10);
    assertEquals(10, stat.getFetchSize());
    stat.setFetchSize(0);
    assertEquals(conf.getInt(FConstants.WASP_JDBC_FETCHSIZE, FConstants.DEFAULT_WASP_JDBC_FETCHSIZE),
            stat.getFetchSize());
    assertEquals(ResultSet.TYPE_FORWARD_ONLY, stat.getResultSetType());
    Statement stat2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY,
            ResultSet.HOLD_CURSORS_OVER_COMMIT);
    assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, stat2.getResultSetType());
    assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, stat2.getResultSetHoldability());
    assertEquals(ResultSet.CONCUR_READ_ONLY, stat2.getResultSetConcurrency());
    assertEquals(0, stat.getMaxFieldSize());
    assertTrue(!((JdbcStatement) stat2).isClosed());
    stat2.close();
    assertTrue(((JdbcStatement) stat2).isClosed());

    ResultSet rs;
    int count;
    boolean result;

    stat.execute("CREATE TABLE TEST {REQUIRED INT64 ID;" + "REQUIRED STRING VALUE; }PRIMARY KEY(ID), "
            + "ENTITY GROUP ROOT,ENTITY GROUP KEY(ID);");

    TEST_UTIL.waitTableEnabled(Bytes.toBytes("TEST"), 5000);

    ResultInHBasePrinter.printMETA(conf, LOG);
    ResultInHBasePrinter.printFMETA(conf, LOG);
    ResultInHBasePrinter.printTable("test", "WASP_ENTITY_TEST", conf, LOG);

    conn.getTypeMap();

    // this method should not throw an exception - if not supported, this
    // calls are ignored

    assertEquals(ResultSet.CONCUR_READ_ONLY, stat.getResultSetConcurrency());

    // stat.cancel();
    stat.setQueryTimeout(10);
    assertTrue(stat.getQueryTimeout() == 10);
    stat.setQueryTimeout(0);
    assertTrue(stat.getQueryTimeout() == 0);
    // assertThrows(SQLErrorCode.INVALID_VALUE_2, stat).setQueryTimeout(-1);
    assertTrue(stat.getQueryTimeout() == 0);
    trace("executeUpdate");
    count = stat.executeUpdate("INSERT INTO TEST (ID,VALUE) VALUES (1,'Hello')");
    assertEquals(1, count);
    count = stat.executeUpdate("INSERT INTO TEST (VALUE,ID) VALUES ('JDBC',2)");
    assertEquals(1, count);
    count = stat.executeUpdate("UPDATE TEST SET VALUE='LDBC' WHERE ID=1");
    assertEquals(1, count);

    count = stat.executeUpdate("DELETE FROM TEST WHERE ID=-1");
    assertEquals(0, count);
    count = stat.executeUpdate("DELETE FROM TEST WHERE ID=1");
    assertEquals(1, count);
    count = stat.executeUpdate("DELETE FROM TEST WHERE ID=2");
    assertEquals(1, count);

    result = stat.execute("INSERT INTO TEST(ID,VALUE) VALUES(1,'Hello')");
    assertTrue(!result);
    result = stat.execute("INSERT INTO TEST(VALUE,ID) VALUES('JDBC',2)");
    assertTrue(!result);
    result = stat.execute("UPDATE TEST SET VALUE='LDBC' WHERE ID=2");
    assertTrue(!result);
    result = stat.execute("DELETE FROM TEST WHERE ID=1");
    assertTrue(!result);
    result = stat.execute("DELETE FROM TEST WHERE ID=2");
    assertTrue(!result);
    result = stat.execute("DELETE FROM TEST WHERE ID=3");
    assertTrue(!result);

    // getMoreResults
    rs = stat.executeQuery("SELECT ID,VALUE FROM TEST WHERE ID=1");
    assertFalse(stat.getMoreResults());
    assertThrows(SQLErrorCode.OBJECT_CLOSED, rs).next();
    assertTrue(stat.getUpdateCount() == -1);
    count = stat.executeUpdate("DELETE FROM TEST WHERE ID=1");
    assertFalse(stat.getMoreResults());
    assertTrue(stat.getUpdateCount() == -1);

    WaspAdmin admin = new WaspAdmin(TEST_UTIL.getConfiguration());
    admin.disableTable("TEST");
    stat.execute("DROP TABLE TEST");
    admin.waitTableNotLocked("TEST".getBytes());
    stat.executeUpdate("DROP TABLE IF EXISTS TEST");

    assertTrue(stat.getWarnings() == null);
    stat.clearWarnings();
    assertTrue(stat.getWarnings() == null);
    assertTrue(conn == stat.getConnection());

    admin.close();
    stat.close();
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static String createJdbcXmlResult(Statement statement)
        throws SQLException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDocumentResult = builder.newDocument();
    Element resultsElement = xmlDocumentResult.createElement("Results");
    xmlDocumentResult.appendChild(resultsElement);

    if (statement != null) {
        ResultSet resultSet = statement.getResultSet();
        if (resultSet != null) {
            resultSet.setFetchSize(statement.getFetchSize());
            xmlDocumentResult = addResultSetXmlPart(resultsElement, resultSet, xmlDocumentResult);
            while (statement.getMoreResults()) {
                xmlDocumentResult = addResultSetXmlPart(resultsElement, statement.getResultSet(),
                        xmlDocumentResult);
            }/* w ww  .  j a va  2  s  .  c  o  m*/
        } else {
            Element errorElement = xmlDocumentResult.createElement("UpdateCount");
            errorElement
                    .appendChild(xmlDocumentResult.createTextNode(String.valueOf(statement.getUpdateCount())));
            resultsElement.appendChild(errorElement);
        }
    }

    StringWriter out = new StringWriter();

    OutputFormat outputFormat = new OutputFormat(xmlDocumentResult);
    outputFormat.setOmitComments(true);
    outputFormat.setOmitDocumentType(true);
    outputFormat.setOmitXMLDeclaration(true);
    // outputFormat.setLineSeparator( "\n" );
    // add this line //
    // outputFormat.setPreserveSpace( true );
    outputFormat.setIndent(3);
    outputFormat.setIndenting(true);

    try {
        XMLSerializer serializer = new XMLSerializer(new PrintWriter(out), outputFormat);
        serializer.asDOMSerializer();
        serializer.serialize(xmlDocumentResult);
    } catch (IOException e) {
        throw new SoapBuilderException(e);
    }

    return out.toString();
}

From source file:edu.arizona.rice.kew.docsearch.dao.impl.DocumentSearchDAOJdbcImpl.java

/**
 * //from  ww  w .  j a  v a  2s . co m
 * @param criteria
 * @param criteriaModified
 * @param searchFields
 * @return 
 */
protected DocumentSearchResults.Builder doInternalSearch(DocumentSearchCriteria criteria,
        boolean criteriaModified, final List<RemotableAttributeField> searchFields) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet res = null;

    DocumentSearchResults.Builder retval = DocumentSearchResults.Builder
            .create(DocumentSearchCriteria.Builder.create(criteria));
    retval.setCriteriaModified(criteriaModified);
    retval.setSearchResults(new ArrayList<DocumentSearchResult.Builder>());

    try {
        conn = dataSource.getConnection();
        conn.setReadOnly(true);
        stmt = conn.createStatement();
        int maxRows = getMaxResultCap(criteria) + 1;

        stmt.setMaxRows(maxRows);

        int fetchSize = stmt.getFetchSize();

        // use default fetch size if document id is included
        // otherwize use custom fetch size
        if (StringUtils.isBlank(criteria.getDocumentId())) {
            fetchSize = customFetchSize;
        }

        String sql = getSearchSql(criteria, searchFields);

        res = stmt.executeQuery(sql);

        // run up to the starting row if required
        if (criteria.getStartAtIndex() != null) {
            for (int i = 0; (i < criteria.getStartAtIndex()) && res.next(); ++i) {
            }
            ;
        }

        List<DocumentInformation> results = new ArrayList<DocumentInformation>();

        // load up document information from the query
        while (res.next() && (results.size() < maxRows)) {
            results.add(new DocumentInformation(res));
        }

        // if we have threshold+1 results, then we have more results than we are going to display
        retval.setOverThreshold(res.next());
        if (isUsingAtLeastOneSearchAttribute(criteria)) {
            // now that we have a list of documents, load the attributes
            loadDocumentAttributes(results, fetchSize);
        }

        // generate the DocumentSearchResults.Builder to return
        for (DocumentInformation docinfo : results) {
            retval.getSearchResults().add(docinfo.getSearchResult());
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("document search result rows processed: " + retval.getSearchResults().size());
        }
    }

    catch (Exception ex) {
        throw new RuntimeException(ex.toString(), ex);
    }

    finally {
        DocumentSearchUtils.closeDbObjects(conn, stmt, res);
    }

    return retval;
}

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

private void doTestSelectAll(String tableName, int maxRows, int fetchSize) throws Exception {
    boolean isPartitionTable = tableName.equals(partitionedTableName);

    Statement stmt = con.createStatement();
    if (maxRows >= 0) {
        stmt.setMaxRows(maxRows);//from  w  w  w  .j a  v a2  s .com
    }
    if (fetchSize > 0) {
        stmt.setFetchSize(fetchSize);
        assertEquals(fetchSize, stmt.getFetchSize());
    }

    // JDBC says that 0 means return all, which is the default
    int expectedMaxRows = maxRows < 1 ? 0 : maxRows;

    assertNotNull("Statement is null", stmt);
    assertEquals("Statement max rows not as expected", expectedMaxRows, stmt.getMaxRows());
    assertFalse("Statement should not be closed", stmt.isClosed());

    ResultSet res;

    // run some queries
    res = stmt.executeQuery("select * from " + tableName);
    assertNotNull("ResultSet is null", res);
    assertTrue("getResultSet() not returning expected ResultSet", res == stmt.getResultSet());
    assertEquals("get update count not as expected", 0, stmt.getUpdateCount());
    int i = 0;

    ResultSetMetaData meta = res.getMetaData();
    int expectedColCount = isPartitionTable ? 3 : 2;
    assertEquals("Unexpected column count", expectedColCount, meta.getColumnCount());

    String colQualifier = ((tableName != null) && !tableName.isEmpty()) ? tableName.toLowerCase() + "." : "";
    boolean moreRow = res.next();
    while (moreRow) {
        try {
            i++;
            assertEquals(res.getInt(1), res.getInt(colQualifier + "under_col"));
            assertEquals(res.getString(1), res.getString(colQualifier + "under_col"));
            assertEquals(res.getString(2), res.getString(colQualifier + "value"));
            if (isPartitionTable) {
                assertEquals(res.getString(3), partitionedColumnValue);
                assertEquals(res.getString(3), res.getString(colQualifier + partitionedColumnName));
            }
            assertFalse("Last result value was not null", res.wasNull());
            assertNull("No warnings should be found on ResultSet", res.getWarnings());
            res.clearWarnings(); // verifying that method is supported

            // System.out.println(res.getString(1) + " " + res.getString(2));
            assertEquals("getInt and getString don't align for the same result value",
                    String.valueOf(res.getInt(1)), res.getString(1));
            assertEquals("Unexpected result found", "val_" + res.getString(1), res.getString(2));
            moreRow = res.next();
        } catch (SQLException e) {
            System.out.println(e.toString());
            e.printStackTrace();
            throw new Exception(e.toString());
        }
    }

    // supposed to get 500 rows if maxRows isn't set
    int expectedRowCount = maxRows > 0 ? maxRows : 500;
    assertEquals("Incorrect number of rows returned", expectedRowCount, i);

    // should have no more rows
    assertEquals(false, moreRow);

    assertNull("No warnings should be found on statement", stmt.getWarnings());
    stmt.clearWarnings(); // verifying that method is supported

    assertNull("No warnings should be found on connection", con.getWarnings());
    con.clearWarnings(); // verifying that method is supported

    stmt.close();
    assertTrue("Statement should be closed", stmt.isClosed());
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

private void doTestSelectAll(String tableName, int maxRows, int fetchSize) throws Exception {
    boolean isPartitionTable = tableName.equals(partitionedTableName);

    Statement stmt = con.createStatement();
    if (maxRows >= 0) {
        stmt.setMaxRows(maxRows);/*w  w  w . ja  v  a  2s.  c  o m*/
    }
    if (fetchSize > 0) {
        stmt.setFetchSize(fetchSize);
        assertEquals(fetchSize, stmt.getFetchSize());
    }

    // JDBC says that 0 means return all, which is the default
    int expectedMaxRows = maxRows < 1 ? 0 : maxRows;

    assertNotNull("Statement is null", stmt);
    assertEquals("Statement max rows not as expected", expectedMaxRows, stmt.getMaxRows());
    assertFalse("Statement should not be closed", stmt.isClosed());

    ResultSet res;

    // run some queries
    res = stmt.executeQuery("select * from " + tableName);
    assertNotNull("ResultSet is null", res);
    assertTrue("getResultSet() not returning expected ResultSet", res == stmt.getResultSet());
    assertEquals("get update count not as expected", -1, stmt.getUpdateCount());
    int i = 0;

    ResultSetMetaData meta = res.getMetaData();
    int expectedColCount = isPartitionTable ? 3 : 2;
    assertEquals("Unexpected column count", expectedColCount, meta.getColumnCount());

    boolean moreRow = res.next();
    while (moreRow) {
        try {
            i++;
            assertEquals(res.getInt(1), res.getInt(tableName + ".under_col"));
            assertEquals(res.getInt(1), res.getInt("under_col"));
            assertEquals(res.getString(1), res.getString(tableName + ".under_col"));
            assertEquals(res.getString(1), res.getString("under_col"));
            assertEquals(res.getString(2), res.getString(tableName + ".value"));
            assertEquals(res.getString(2), res.getString("value"));
            if (isPartitionTable) {
                assertEquals(res.getString(3), partitionedColumnValue);
                assertEquals(res.getString(3), res.getString(partitionedColumnName));
                assertEquals(res.getString(3), res.getString(tableName + "." + partitionedColumnName));
            }
            assertFalse("Last result value was not null", res.wasNull());
            assertNull("No warnings should be found on ResultSet", res.getWarnings());
            res.clearWarnings(); // verifying that method is supported

            // System.out.println(res.getString(1) + " " + res.getString(2));
            assertEquals("getInt and getString don't align for the same result value",
                    String.valueOf(res.getInt(1)), res.getString(1));
            assertEquals("Unexpected result found", "val_" + res.getString(1), res.getString(2));
            moreRow = res.next();
        } catch (SQLException e) {
            System.out.println(e.toString());
            e.printStackTrace();
            throw new Exception(e.toString());
        }
    }

    // supposed to get 500 rows if maxRows isn't set
    int expectedRowCount = maxRows > 0 ? maxRows : 500;
    assertEquals("Incorrect number of rows returned", expectedRowCount, i);

    // should have no more rows
    assertEquals(false, moreRow);

    assertNull("No warnings should be found on statement", stmt.getWarnings());
    stmt.clearWarnings(); // verifying that method is supported

    assertNull("No warnings should be found on connection", con.getWarnings());
    con.clearWarnings(); // verifying that method is supported

    stmt.close();
    assertTrue("Statement should be closed", stmt.isClosed());
}