List of usage examples for java.sql Statement setQueryTimeout
void setQueryTimeout(int seconds) throws SQLException;
Statement
object to execute to the given number of seconds. From source file:org.talend.core.model.metadata.builder.database.ExtractMetaDataUtils.java
/** * /*from w w w . ja v a2 s. c o m*/ * ggu Comment method "setQueryStatementTimeout". * * @param statement */ public void setQueryStatementTimeout(Statement statement) { if (statement != null) { try { if (isIgnoreTimeout()) { statement.setQueryTimeout(0); } else { statement.setQueryTimeout(getDBConnectionTimeout()); } } catch (SQLException e) { // nothing, some db doesn't support the timeout // no need to throw exception or this one will be throw all the time } } }
From source file:org.nuclos.server.dblayer.impl.standard.StandardSqlDBAccess.java
protected boolean setStatementHint(Statement stmt, String hint, Object value) throws SQLException { if (MAX_ROWS_HINT.equals(hint)) { stmt.setMaxRows((Integer) value); return true; } else if (QUERY_TIMEOUT_HINT.equals(hint)) { stmt.setQueryTimeout((Integer) value); return true; }//from w w w . j ava 2s. c o m return false; }
From source file:org.opoo.oqs.core.AbstractQuery.java
protected void applyStatementSettings(Statement stmt) throws SQLException { int fetchSize = getFetchSize(); if (fetchSize > 0) { stmt.setFetchSize(fetchSize);// w w w . j a v a 2s .c o m } int maxRows = getMaxRows(); if (maxRows > 0) { stmt.setMaxRows(maxRows); } int timeout = getQueryTimeout(); if (timeout > 0) { stmt.setQueryTimeout(timeout); } }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCwoTimeOutTestElement.java
/** * Execute the test element.// w w w. java 2 s . c om * * @param conn a {@link SampleResult} in case the test should sample; <code>null</code> if only execution is requested * @throws UnsupportedOperationException if the user provided incorrect query type */ @Override protected byte[] execute(final Connection conn) throws SQLException, UnsupportedEncodingException, IOException, UnsupportedOperationException { log.debug("executing jdbc"); Statement stmt = null; try { // Based on query return value, get results final String _queryType = getQueryType(); if (SELECT.equals(_queryType)) { stmt = conn.createStatement(); //stmt.setQueryTimeout(getIntegerQueryTimeout()); ResultSet rs = null; try { final String query = getQuery(); System.out.println(query); rs = stmt.executeQuery(query); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (CALLABLE.equals(_queryType)) { final CallableStatement cstmt = getCallableStatement(conn); final int out[] = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. final boolean hasResultSet = cstmt.execute(); final String sb = resultSetsToString(cstmt, hasResultSet, out); return sb.getBytes(ENCODING); } else if (UPDATE.equals(_queryType)) { stmt = conn.createStatement(); stmt.setQueryTimeout(getIntegerQueryTimeout()); stmt.executeUpdate(getQuery()); final int updateCount = stmt.getUpdateCount(); final String results = updateCount + " updates"; return results.getBytes(ENCODING); } else if (PREPARED_SELECT.equals(_queryType)) { final PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); System.out.println(pstmt); ResultSet rs = null; try { rs = pstmt.executeQuery(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (PREPARED_UPDATE.equals(_queryType)) { final PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); pstmt.executeUpdate(); final String sb = resultSetsToString(pstmt, false, null); return sb.getBytes(ENCODING); } else if (ROLLBACK.equals(_queryType)) { conn.rollback(); return ROLLBACK.getBytes(ENCODING); } else if (COMMIT.equals(_queryType)) { conn.commit(); return COMMIT.getBytes(ENCODING); } else if (AUTOCOMMIT_FALSE.equals(_queryType)) { conn.setAutoCommit(false); return AUTOCOMMIT_FALSE.getBytes(ENCODING); } else if (AUTOCOMMIT_TRUE.equals(_queryType)) { conn.setAutoCommit(true); return AUTOCOMMIT_TRUE.getBytes(ENCODING); } else { // User provided incorrect query type throw new UnsupportedOperationException("Unexpected query type: " + _queryType); } } finally { close(stmt); } }
From source file:org.apache.hive.beeline.BeeLine.java
Statement createStatement() throws SQLException { Statement stmnt = getDatabaseConnection().getConnection().createStatement(); if (getOpts().timeout > -1) { stmnt.setQueryTimeout(getOpts().timeout); }/*from ww w . j a v a 2 s. c o m*/ if (signalHandler != null) { signalHandler.setStatement(stmnt); } return stmnt; }
From source file:com.hangum.tadpole.rdb.core.editors.main.composite.ResultSetComposite.java
/** * .//from w ww . j a va 2 s . com * * @param reqQuery * @param queryTimeOut * @param strUserEmail * @param intSelectLimitCnt * @param intStartCnt * @param strNullValue * @return * @throws Exception */ public QueryExecuteResultDTO runSelect(final RequestQuery reqQuery, final int queryTimeOut, final String strUserEmail, final int intSelectLimitCnt, final int intStartCnt) throws Exception { String strSQL = reqQuery.getSql(); if (!PermissionChecker.isExecute(getDbUserRoleType(), getUserDB(), strSQL)) { throw new Exception(Messages.get().MainEditor_21); } if (logger.isDebugEnabled()) logger.debug("==> real execute query : " + strSQL); tadpole_system_message = ""; QueryExecuteResultDTO queryResultDAO = null; // ?? ??? . IMainEditorExtension[] extensions = getRdbResultComposite().getMainEditor().getMainEditorExtions(); if (extensions != null) { for (IMainEditorExtension iMainEditorExtension : extensions) { String strCostumSQL = iMainEditorExtension.sqlCostume(strSQL); if (!strCostumSQL.equals(strSQL)) { if (logger.isDebugEnabled()) logger.debug("** extension costume sql is : " + strCostumSQL); //$NON-NLS-1$ strSQL = strCostumSQL; } } } // ?? ??? . ResultSet resultSet = null; java.sql.Connection javaConn = null; Statement statement = null; PreparedStatement preparedStatement = null; try { if (DBGroupDefine.TAJO_GROUP == getUserDB().getDBGroup()) { javaConn = ConnectionPoolManager.getDataSource(getUserDB()).getConnection(); } else { if (reqQuery.isAutoCommit()) { SqlMapClient client = TadpoleSQLManager.getInstance(getUserDB()); javaConn = client.getDataSource().getConnection(); } else { javaConn = TadpoleSQLTransactionManager.getInstance(strUserEmail, getUserDB()); } } if (javaConn == null) { throw new Exception("Cann't create session. Please check system."); } // if statement type is prepared statement? if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.NONE) { statement = javaConn.createStatement(); statement.setFetchSize(intSelectLimitCnt); if (DBGroupDefine.HIVE_GROUP != getUserDB().getDBGroup()) { statement.setQueryTimeout(queryTimeOut); statement.setMaxRows(intSelectLimitCnt); } // check stop thread esCheckStop = Executors.newSingleThreadExecutor(); CheckStopThread cst = new CheckStopThread(statement); cst.setName("TDB Query Stop checker"); //$NON-NLS-1$ esCheckStop.execute(cst); // execute query execServiceQuery = Executors.newSingleThreadExecutor(); if (intStartCnt == 0) { resultSet = _runSQLSelect(statement, strSQL); } else { strSQL = PartQueryUtil.makeSelect(getUserDB(), strSQL, intStartCnt, intSelectLimitCnt); if (logger.isDebugEnabled()) logger.debug("part sql called : " + strSQL); resultSet = _runSQLSelect(statement, strSQL); } } else if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.PREPARED_STATEMENT) { preparedStatement = javaConn.prepareStatement(strSQL); preparedStatement.setFetchSize(intSelectLimitCnt); if (DBGroupDefine.HIVE_GROUP != getUserDB().getDBGroup()) { preparedStatement.setQueryTimeout(queryTimeOut); preparedStatement.setMaxRows(intSelectLimitCnt); } // check stop thread esCheckStop = Executors.newSingleThreadExecutor(); CheckStopThread cst = new CheckStopThread(preparedStatement); cst.setName("TDB Query Stop checker"); //$NON-NLS-1$ esCheckStop.execute(cst); // execute query execServiceQuery = Executors.newSingleThreadExecutor(); if (intStartCnt == 0) { resultSet = _runSQLSelect(preparedStatement, reqQuery.getStatementParameter()); } else { strSQL = PartQueryUtil.makeSelect(getUserDB(), strSQL, intStartCnt, intSelectLimitCnt); if (logger.isDebugEnabled()) logger.debug("part sql called : " + strSQL); resultSet = _runSQLSelect(preparedStatement, reqQuery.getStatementParameter()); } } queryResultDAO = new QueryExecuteResultDTO(getUserDB(), reqQuery.getSql(), true, resultSet, intSelectLimitCnt, intStartCnt); if (resultSet == null) { if (StringUtils.isEmpty(StringUtils.deleteWhitespace(tadpole_system_message))) { tadpole_system_message = CMD_COMPLETE_MSG; } } queryResultDAO.setQueryMsg(tadpole_system_message); } catch (Exception e) { throw e; } finally { isCheckRunning = false; try { if (preparedStatement != null) preparedStatement.close(); } catch (Exception e) { } try { if (statement != null) statement.close(); } catch (Exception e) { } try { if (resultSet != null) resultSet.close(); } catch (Exception e) { } if (reqQuery.isAutoCommit()) { try { if (javaConn != null) javaConn.close(); } catch (Exception e) { } } } return queryResultDAO; }
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.ja va 2s. 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.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.SimpleSQLReportDataFactory.java
protected TableModel parametrizeAndQuery(final DataRow parameters, final String translatedQuery, final String[] preparedParameterNames) throws SQLException { final boolean callableStatementQuery = isCallableStatementQuery(translatedQuery); final boolean callableStatementUsed = callableStatementQuery || isCallableStatement(translatedQuery); final Statement statement; if (preparedParameterNames.length == 0) { statement = getConnection(parameters).createStatement(getBestResultSetType(parameters), ResultSet.CONCUR_READ_ONLY); } else {//w w w. j a v a2 s. c om if (callableStatementUsed) { final CallableStatement pstmt = getConnection(parameters).prepareCall(translatedQuery, getBestResultSetType(parameters), ResultSet.CONCUR_READ_ONLY); if (isCallableStatementQuery(translatedQuery)) { pstmt.registerOutParameter(1, Types.OTHER); parametrize(parameters, preparedParameterNames, pstmt, false, 1); } else { parametrize(parameters, preparedParameterNames, pstmt, false, 0); } statement = pstmt; } else { final PreparedStatement pstmt = getConnection(parameters).prepareStatement(translatedQuery, getBestResultSetType(parameters), ResultSet.CONCUR_READ_ONLY); parametrize(parameters, preparedParameterNames, pstmt, isExpandArrays(), 0); statement = pstmt; } } final Object queryLimit = parameters.get(DataFactory.QUERY_LIMIT); try { if (queryLimit instanceof Number) { final Number i = (Number) queryLimit; final int max = i.intValue(); if (max > 0) { statement.setMaxRows(max); } } } catch (SQLException sqle) { // this fails for MySQL as their driver is buggy. We will not add workarounds here, as // all drivers are buggy and this is a race we cannot win. Put pressure on the driver // manufacturer instead. logger.warn("Driver indicated error: Failed to set query-limit: " + queryLimit, sqle); } final Object queryTimeout = parameters.get(DataFactory.QUERY_TIMEOUT); try { if (queryTimeout instanceof Number) { final Number i = (Number) queryTimeout; final int seconds = i.intValue(); if (seconds > 0) { statement.setQueryTimeout(seconds); } } } catch (SQLException sqle) { logger.warn("Driver indicated error: Failed to set query-timeout: " + queryTimeout, sqle); } // Track the currently running statement - just in case someone needs to cancel it final ResultSet res; try { currentRunningStatement = statement; if (preparedParameterNames.length == 0) { res = statement.executeQuery(translatedQuery); } else { final PreparedStatement pstmt = (PreparedStatement) statement; res = pstmt.executeQuery(); } } finally { currentRunningStatement = null; } // equalsIgnore, as this is what the ResultSetTableModelFactory uses. final boolean simpleMode = "simple".equalsIgnoreCase(getConfiguration().getConfigProperty( //$NON-NLS-1$ ResultSetTableModelFactory.RESULTSET_FACTORY_MODE)); //$NON-NLS-1$ if (simpleMode) { return ResultSetTableModelFactory.getInstance().generateDefaultTableModel(res, columnNameMapping); } return ResultSetTableModelFactory.getInstance().createTableModel(res, columnNameMapping, true); }
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 ww . ja v a 2 s . 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; }
From source file:org.ramadda.repository.database.DatabaseManager.java
/** * _more_/*from w w w .j av a 2s . c o m*/ * * @param connection _more_ * @param sql _more_ * @param max _more_ * @param timeout _more_ * * @return _more_ * * @throws Exception _more_ */ public Statement execute(Connection connection, String sql, int max, int timeout) throws Exception { Statement statement = connection.createStatement(); if (timeout > 0) { statement.setQueryTimeout(timeout); } if (max > 0) { statement.setMaxRows(max); } long t1 = System.currentTimeMillis(); try { statement.execute(sql); } catch (Exception exc) { // logError("Error executing sql:" + sql, exc); throw exc; } long t2 = System.currentTimeMillis(); if (getRepository().debug || (t2 - t1 > 300)) { logInfo("query took:" + (t2 - t1) + " " + sql); } if (t2 - t1 > 2000) { // Misc.printStack("query:" + sql); } return statement; }