Example usage for java.sql Statement getQueryTimeout

List of usage examples for java.sql Statement getQueryTimeout

Introduction

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

Prototype

int getQueryTimeout() throws SQLException;

Source Link

Document

Retrieves the number of seconds the driver will wait for a Statement object to execute.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Statement statement = null;
    String url = "jdbc:odbc:databaseName";
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String username = "guest";
    String password = "guest";
    Class.forName(driver);//  w  ww.j  av  a2  s  .  c o  m
    Connection connection = DriverManager.getConnection(url, username, password);
    statement = connection.createStatement();
    System.out.println("Driver          :  " + driver);

    // Put each method call in a separate try block to execute them all
    System.out.print("\nMaximum rows    :");
    int maxRows = statement.getMaxRows();
    System.out.print(maxRows == 0 ? " No limit" : " " + maxRows);

    System.out.print("\nMax field size  :");
    int maxFieldSize = statement.getMaxFieldSize();
    System.out.print(maxFieldSize == 0 ? " No limit" : " " + maxFieldSize);

    System.out.print("\nTimeout          :");
    int queryTimeout = statement.getQueryTimeout();
    System.out.print(queryTimeout == 0 ? " No limit" : " " + queryTimeout);

}

From source file:fr.calamus.common.db.core.DbPool.java

private Statement getStatement(String key) {
    try {/*from   w  w w  .j  a v a  2  s.  c  o  m*/
        Statement st = stMap.get(key);
        if (st == null || st.isClosed()) {
            log("creating statement");
            st = createStatement(key);
        } else {
            log("returning existing statement " + st.getQueryTimeout());
        }
        return st;
    } catch (SQLException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.mapd.bench.Benchmark.java

String executeQuery(String sql, int expected, int iterations, int queryNum) {
    Connection conn = null;//  ww w  . j a v  a 2  s  .  c  o  m
    Statement stmt = null;

    Long firstExecute = 0l;
    Long firstJdbc = 0l;
    Long firstIterate = 0l;

    DescriptiveStatistics statsExecute = new DescriptiveStatistics();
    DescriptiveStatistics statsJdbc = new DescriptiveStatistics();
    DescriptiveStatistics statsIterate = new DescriptiveStatistics();
    DescriptiveStatistics statsTotal = new DescriptiveStatistics();

    long totalTime = 0;

    try {
        //Open a connection
        logger.debug("Connecting to database url :" + url);
        conn = DriverManager.getConnection(url, iUser, iPasswd);

        long startTime = System.currentTimeMillis();
        for (int loop = 0; loop < iterations; loop++) {

            //Execute a query
            stmt = conn.createStatement();

            long timer = System.currentTimeMillis();
            ResultSet rs = stmt.executeQuery(sql);

            long executeTime = 0;
            long jdbcTime = 0;

            // gather internal execute time for MapD as we are interested in that
            if (driver.equals(JDBC_DRIVER)) {
                executeTime = stmt.getQueryTimeout();
                jdbcTime = (System.currentTimeMillis() - timer) - executeTime;
            } else {
                jdbcTime = (System.currentTimeMillis() - timer);
                executeTime = 0;
            }
            // this is fake to get our intenal execute time.
            logger.debug("Query Timeout/AKA internal Execution Time was " + stmt.getQueryTimeout()
                    + " ms Elapsed time in JVM space was " + (System.currentTimeMillis() - timer) + "ms");

            timer = System.currentTimeMillis();
            //Extract data from result set
            int resultCount = 0;
            while (rs.next()) {
                Object obj = rs.getObject(1);
                if (obj != null && obj.equals(statsExecute)) {
                    logger.info("Impossible");
                }
                resultCount++;
            }
            long iterateTime = (System.currentTimeMillis() - timer);

            if (resultCount != expected) {
                logger.error("Expect " + expected + " actual " + resultCount + " for query " + sql);
                // don't run anymore
                break;
            }

            if (loop == 0) {
                firstJdbc = jdbcTime;
                firstExecute = executeTime;
                firstIterate = iterateTime;

            } else {
                statsJdbc.addValue(jdbcTime);
                statsExecute.addValue(executeTime);
                statsIterate.addValue(iterateTime);
                statsTotal.addValue(jdbcTime + executeTime + iterateTime);
            }

            //Clean-up environment
            rs.close();
            stmt.close();
        }
        totalTime = System.currentTimeMillis() - startTime;
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    } //end try

    return String.format(lineDescriptor, queryNum, statsTotal.getMean(), statsTotal.getMin(),
            statsTotal.getMax(), statsTotal.getPercentile(85), statsExecute.getMean(), statsExecute.getMin(),
            statsExecute.getMax(), statsExecute.getPercentile(85), statsExecute.getPercentile(25),
            statsExecute.getStandardDeviation(), statsJdbc.getMean(), statsJdbc.getMin(), statsJdbc.getMax(),
            statsJdbc.getPercentile(85), statsIterate.getMean(), statsIterate.getMin(), statsIterate.getMax(),
            statsIterate.getPercentile(85), firstExecute, firstJdbc, firstIterate, iterations, totalTime,
            (long) statsTotal.getSum() + firstExecute + firstJdbc + firstIterate);

}

From source file:com.mapd.bench.BenchmarkCloud.java

String executeQuery(Connection conn1, String qid, String sql, int iterations) {
    Statement stmt = null;
    Connection conn = getConnection(url, iUser, iPasswd);

    Long firstExecute = 0l;//from   w w  w. j a v a  2  s  .  c o  m
    Long firstJdbc = 0l;
    Long firstIterate = 0l;

    DescriptiveStatistics statsExecute = new DescriptiveStatistics();
    DescriptiveStatistics statsJdbc = new DescriptiveStatistics();
    DescriptiveStatistics statsIterate = new DescriptiveStatistics();
    DescriptiveStatistics statsTotal = new DescriptiveStatistics();

    long totalTime = 0;
    int resultCount = 0;
    try {

        long startTime = System.currentTimeMillis();
        for (int loop = 0; loop < iterations; loop++) {

            //Execute a query
            stmt = conn.createStatement();

            long timer = System.currentTimeMillis();
            if (loop == 0) {
                System.out.println(String.format("Query Id is %s : query is '%s'", qid, sql));
            }
            ResultSet rs = stmt.executeQuery(sql);

            long executeTime = 0;
            long jdbcTime = 0;

            // gather internal execute time for MapD as we are interested in that
            if (driver.equals(JDBC_DRIVER)) {
                executeTime = stmt.getQueryTimeout();
                jdbcTime = (System.currentTimeMillis() - timer) - executeTime;
            } else {
                jdbcTime = (System.currentTimeMillis() - timer);
                executeTime = 0;
            }
            // this is fake to get our intenal execute time.
            logger.debug("Query Timeout/AKA internal Execution Time was " + stmt.getQueryTimeout()
                    + " ms Elapsed time in JVM space was " + (System.currentTimeMillis() - timer) + "ms");

            timer = System.currentTimeMillis();
            //Extract data from result set
            resultCount = 0;
            while (rs.next()) {
                Object obj = rs.getObject(1);
                if (obj != null && obj.equals(statsExecute)) {
                    logger.info("Impossible");
                }
                resultCount++;
            }
            long iterateTime = (System.currentTimeMillis() - timer);

            //        if (resultCount != expected) {
            //          logger.error("Expect " + expected + " actual " + resultCount + " for query " + sql);
            //          // don't run anymore
            //          break;
            //        }
            if (loop == 0) {
                firstJdbc = jdbcTime;
                firstExecute = executeTime;
                firstIterate = iterateTime;

            } else {
                statsJdbc.addValue(jdbcTime);
                statsExecute.addValue(executeTime);
                statsIterate.addValue(iterateTime);
                statsTotal.addValue(jdbcTime + executeTime + iterateTime);
            }

            //Clean-up environment
            rs.close();
            stmt.close();
        }
        totalTime = System.currentTimeMillis() - startTime;
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
        System.exit(4);
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
        System.exit(3);
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
            System.exit(6);
        } //end finally try
    } //end try

    // write it to the db here as well
    String insertPart = String.format(insertDescriptor, this.rid, this.rTimestamp, url, this.driver, label,
            gpuCount, this.tableName, qid, resultCount, "", statsTotal.getMean(), statsTotal.getMin(),
            statsTotal.getMax(), statsTotal.getPercentile(85), statsExecute.getMean(), statsExecute.getMin(),
            statsExecute.getMax(), statsExecute.getPercentile(85), statsExecute.getPercentile(25),
            statsExecute.getStandardDeviation(), statsJdbc.getMean(), statsJdbc.getMin(), statsJdbc.getMax(),
            statsJdbc.getPercentile(85), statsIterate.getMean(), statsIterate.getMin(), statsIterate.getMax(),
            statsIterate.getPercentile(85), firstExecute, firstJdbc, firstIterate, iterations, totalTime,
            (long) statsTotal.getSum() + firstExecute + firstJdbc + firstIterate, targetDBVersion);

    LResult.add("Insert into results values " + insertPart);

    return String.format(lineDescriptor, qid, statsTotal.getMean(), statsTotal.getMin(), statsTotal.getMax(),
            statsTotal.getPercentile(85), statsExecute.getMean(), statsExecute.getMin(), statsExecute.getMax(),
            statsExecute.getPercentile(85), statsExecute.getPercentile(25), statsExecute.getStandardDeviation(),
            statsJdbc.getMean(), statsJdbc.getMin(), statsJdbc.getMax(), statsJdbc.getPercentile(85),
            statsIterate.getMean(), statsIterate.getMin(), statsIterate.getMax(),
            statsIterate.getPercentile(85), firstExecute, firstJdbc, firstIterate, iterations, totalTime,
            (long) statsTotal.getSum() + firstExecute + firstJdbc + firstIterate);

}

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//from   w  ww  .  j a va  2 s.  c o  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:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

private AggMetricValue[] getHistDataSet(Integer[] mids, long start, long finish, long rangeBegin, long rangeEnd,
        long windowSize, final boolean returnNulls, AtomicLong publishedInterval, String threadName) {
    final CharSequence sqlBuf = getRawDataSql(mids, rangeBegin, rangeEnd, publishedInterval);
    final int buckets = (int) ((finish - start) / windowSize);
    final AggMetricValue[] array = new AggMetricValue[buckets];
    Connection conn = null;/*from   w w  w.  j a  v a 2s  .c  o m*/
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = safeGetConnection();
        stmt = conn.createStatement();
        int timeout = stmt.getQueryTimeout();
        if (timeout == 0) {
            stmt.setQueryTimeout(transactionTimeout);
        }
        rs = stmt.executeQuery("/* " + threadName + " */ " + sqlBuf.toString());
        final int sumValCol = rs.findColumn("sumvalue");
        final int countValCol = rs.findColumn("cnt");
        final int minValCol = rs.findColumn("minvalue");
        final int maxValCol = rs.findColumn("maxvalue");
        final int timestampCol = rs.findColumn("timestamp");
        while (rs.next()) {
            final double sum = rs.getDouble(sumValCol);
            final double min = rs.getDouble(minValCol);
            final double max = rs.getDouble(maxValCol);
            final int count = rs.getInt(countValCol);
            final long timestamp = rs.getLong(timestampCol);
            final AggMetricValue val = new AggMetricValue(timestamp, sum, max, min, count);
            if ((timestamp < start) || (timestamp > finish)) {
                continue;
            }
            final int bucket = (int) (buckets - ((finish - timestamp) / (float) windowSize));
            if (bucket < 0) {
                continue;
            }
            merge(bucket, array, val, timestamp);
        }
    } catch (SQLException e) {
        throw new SystemException(e);
    } finally {
        DBUtil.closeJDBCObjects(getClass().getName(), conn, stmt, rs);
    }
    return array;
}