List of usage examples for java.sql PreparedStatement setQueryTimeout
void setQueryTimeout(int seconds) throws SQLException;
Statement
object to execute to the given number of seconds. From source file:io.cloudslang.content.database.services.SQLCommandService.java
public static String executeSqlCommand(final SQLInputs sqlInputs) throws Exception { final ConnectionService connectionService = new ConnectionService(); try (final Connection connection = connectionService.setUpConnection(sqlInputs)) { connection.setReadOnly(false);/*from w ww . j a v a2s .c om*/ final String dbType = sqlInputs.getDbType(); if (ORACLE_DB_TYPE.equalsIgnoreCase(dbType) && sqlInputs.getSqlCommand().toLowerCase().contains(DBMS_OUTPUT)) { final PreparedStatement preparedStatement = connection.prepareStatement(sqlInputs.getSqlCommand()); preparedStatement.setQueryTimeout(sqlInputs.getTimeout()); OracleDbmsOutput oracleDbmsOutput = new OracleDbmsOutput(connection); preparedStatement.executeQuery(); sqlInputs.setIUpdateCount(preparedStatement.getUpdateCount()); preparedStatement.close(); final String output = oracleDbmsOutput.getOutput(); oracleDbmsOutput.close(); return output; } else { final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency()); statement.setQueryTimeout(sqlInputs.getTimeout()); try { statement.execute(sqlInputs.getSqlCommand()); } catch (SQLException e) { if (SYBASE_DB_TYPE.equalsIgnoreCase(dbType)) { //during a dump sybase sends back status as exceptions. if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dump")) { return SQLUtils.processDumpException(e); } else if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("load")) { return SQLUtils.processLoadException(e); } } else { throw e; } } ResultSet rs = statement.getResultSet(); if (rs != null) { ResultSetMetaData rsMtd = rs.getMetaData(); if (rsMtd != null) { sqlInputs.getLRows().clear(); int colCount = rsMtd.getColumnCount(); if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) { while (rs.next()) { if (colCount >= 4) { sqlInputs.getLRows().add(rs.getString(4)); } } } else { String delimiter = (StringUtils.isNoneEmpty(sqlInputs.getStrDelim())) ? sqlInputs.getStrDelim() : ","; String strRowHolder; while (rs.next()) { strRowHolder = ""; for (int i = 1; i <= colCount; i++) { if (i > 1) { strRowHolder += delimiter; } strRowHolder += rs.getString(i); } sqlInputs.getLRows().add(strRowHolder); } } rs.close(); } } //For sybase, when dbcc command is executed, the result is shown in warning message else if (dbType.equalsIgnoreCase(SYBASE_DB_TYPE) && sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) { SQLWarning warning = statement.getWarnings(); while (warning != null) { sqlInputs.getLRows().add(warning.getMessage()); warning = warning.getNextWarning(); } } sqlInputs.setIUpdateCount(statement.getUpdateCount()); } } return "Command completed successfully"; }
From source file:com.microsoft.sqlserver.jdbc.connection.PoolingTest.java
/** * setup connection, get connection from pool, and test threads * /*from ww w . ja va 2 s . com*/ * @param ds * @throws SQLException */ private static void connect(DataSource ds) throws SQLException { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { con = ds.getConnection(); pst = con.prepareStatement("SELECT SUSER_SNAME()"); pst.setQueryTimeout(5); rs = pst.executeQuery(); // TODO : we are commenting this out due to AppVeyor failures. Will investigate later. // assertTrue(countTimeoutThreads() >= 1, "Timeout timer is missing."); while (rs.next()) { rs.getString(1); } } finally { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } }
From source file:com.xqdev.sql.MLSQL.java
private static void configureStatement(PreparedStatement stmt, int maxRows, int queryTimeout, int maxFieldSize) throws SQLException { if (maxRows != -1) { stmt.setMaxRows(maxRows);/*from w ww . j a v a 2 s . c om*/ } if (queryTimeout != -1) { stmt.setQueryTimeout(queryTimeout); } if (maxFieldSize != -1) { stmt.setMaxFieldSize(maxFieldSize); } }
From source file:org.guzz.web.context.spring.TransactionManagerUtils.java
/** * Apply the current transaction timeout, if any, to the given * Guzz Query object.//from w ww . ja v a2 s .com * @param query the Guzz Query object * @param transactionManager Guzz TransactionManager that the Query was created for * (may be <code>null</code>) * @see org.hibernate.Query#setTimeout */ public static void applyTransactionTimeout(PreparedStatement pstm, TransactionManager transactionManager) { Assert.notNull(pstm, "No PreparedStatement object specified"); if (transactionManager != null) { WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager .getResource(transactionManager); if (writeTranSessionHolder != null && writeTranSessionHolder.hasTimeout()) { try { pstm.setQueryTimeout(writeTranSessionHolder.getTimeToLiveInSeconds()); } catch (SQLException e) { throw new DataAccessResourceFailureException(e.getMessage(), e); } } } }
From source file:com.thinkbiganalytics.ingest.GetTableDataSupport.java
/** * Provides an incremental select based on a date field and last status. The overlap time will be subtracted from * the last load date. This will cause duplicate records but also pickup records that were missed on the last scan * due to long-running transactions./*w w w . j a v a 2 s . co m*/ * * @param tableName the table * @param dateField the name of the field containing last modified date used to perform the incremental load * @param overlapTime the number of seconds to overlap with the last load status * @param lastLoadDate the last batch load date */ public ResultSet selectIncremental(String tableName, String[] selectFields, String dateField, int overlapTime, Date lastLoadDate, int backoffTime, UnitSizes unit) throws SQLException { ResultSet rs = null; logger.info( "selectIncremental tableName {} dateField {} overlapTime {} lastLoadDate {} backoffTime {} unit {}", tableName, dateField, overlapTime, lastLoadDate, backoffTime, unit.toString()); final Date now = new Date(DateTimeUtils.currentTimeMillis()); DateRange range = new DateRange(lastLoadDate, now, overlapTime, backoffTime, unit); logger.info("Load range with min {} max {}", range.getMinDate(), range.getMaxDate()); StringBuilder sb = new StringBuilder(); String select = selectStatement(selectFields, "tbl"); sb.append("select ").append(select).append(" from ").append(tableName).append(" tbl WHERE tbl.") .append(dateField).append(" > ? and tbl.").append(dateField).append(" < ?"); if (range.getMinDate().before(range.getMaxDate())) { PreparedStatement ps = conn.prepareStatement(sb.toString()); ps.setQueryTimeout(timeout); ps.setTimestamp(1, new java.sql.Timestamp(range.getMinDate().getTime())); ps.setTimestamp(2, new java.sql.Timestamp(range.getMaxDate().getTime())); logger.info("Executing incremental GetTableData query {}", ps); rs = ps.executeQuery(); } return rs; }
From source file:chh.utils.db.source.common.JdbcClient.java
public void executeInsertQuery(String query, List<List<Column>> columnLists) { Connection connection = null; try {/*w w w . j a va 2 s. co m*/ connection = connectionProvider.getConnection(); boolean autoCommit = connection.getAutoCommit(); if (autoCommit) { connection.setAutoCommit(false); } LOG.debug("Executing query {}", query); PreparedStatement preparedStatement = connection.prepareStatement(query); if (queryTimeoutSecs > 0) { preparedStatement.setQueryTimeout(queryTimeoutSecs); } for (List<Column> columnList : columnLists) { setPreparedStatementParams(preparedStatement, columnList); preparedStatement.addBatch(); } int[] results = preparedStatement.executeBatch(); if (Arrays.asList(results).contains(Statement.EXECUTE_FAILED)) { connection.rollback(); throw new RuntimeException( "failed at least one sql statement in the batch, operation rolled back."); } else { try { connection.commit(); } catch (SQLException e) { throw new RuntimeException("Failed to commit insert query " + query, e); } } } catch (SQLException e) { throw new RuntimeException("Failed to execute insert query " + query, e); } finally { closeConnection(connection); } }
From source file:chh.utils.db.source.common.JdbcClient.java
public List<List<Column>> select(String sqlQuery, List<Column> queryParams) { Connection connection = null; try {//from w ww . j a va2 s. co m connection = connectionProvider.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery); if (queryTimeoutSecs > 0) { preparedStatement.setQueryTimeout(queryTimeoutSecs); } setPreparedStatementParams(preparedStatement, queryParams); ResultSet resultSet = preparedStatement.executeQuery(); List<List<Column>> rows = Lists.newArrayList(); while (resultSet.next()) { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<Column> row = Lists.newArrayList(); for (int i = 1; i <= columnCount; i++) { String columnLabel = metaData.getColumnLabel(i); int columnType = metaData.getColumnType(i); Class columnJavaType = Util.getJavaType(columnType); if (columnJavaType.equals(String.class)) { row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType)); } else if (columnJavaType.equals(Integer.class)) { row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType)); } else if (columnJavaType.equals(Double.class)) { row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType)); } else if (columnJavaType.equals(Float.class)) { row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType)); } else if (columnJavaType.equals(Short.class)) { row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType)); } else if (columnJavaType.equals(Boolean.class)) { row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType)); } else if (columnJavaType.equals(byte[].class)) { row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType)); } else if (columnJavaType.equals(Long.class)) { row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType)); } else if (columnJavaType.equals(Date.class)) { row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType)); } else if (columnJavaType.equals(Time.class)) { row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType)); } else if (columnJavaType.equals(Timestamp.class)) { row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel), columnType)); } else { throw new RuntimeException( "type = " + columnType + " for column " + columnLabel + " not supported."); } } rows.add(row); } return rows; } catch (SQLException e) { throw new RuntimeException("Failed to execute select query " + sqlQuery, e); } finally { closeConnection(connection); } }
From source file:com.amazon.carbonado.repo.jdbc.JDBCStorage.java
static PreparedStatement prepareStatement(Connection con, String sql, Query.Controller controller) throws SQLException { PreparedStatement ps = con.prepareStatement(sql); if (controller != null) { long timeout = controller.getTimeout(); if (timeout >= 0) { TimeUnit unit = controller.getTimeoutUnit(); if (unit != null) { long seconds = unit.toSeconds(timeout); int intSeconds = seconds <= 0 ? 1 : (seconds <= Integer.MAX_VALUE ? ((int) seconds) : 0); ps.setQueryTimeout(intSeconds); }/* www. j a v a 2 s . c o m*/ } } return ps; }
From source file:com.hortonworks.registries.storage.impl.jdbc.provider.sql.statement.PreparedStatementBuilder.java
/** Creates the prepared statement with the parameters in place to be replaced */ private void setPreparedStatement(boolean returnGeneratedKeys) throws SQLException { final String parameterizedSql = sqlBuilder.getParametrizedSql(); log.debug("Creating prepared statement for parameterized sql [{}]", parameterizedSql); final PreparedStatement preparedStatement; if (returnGeneratedKeys) { preparedStatement = connection.prepareStatement(parameterizedSql, Statement.RETURN_GENERATED_KEYS); } else {// ww w. j ava 2 s .c om preparedStatement = connection.prepareStatement(parameterizedSql); } final int queryTimeoutSecs = config.getQueryTimeoutSecs(); if (queryTimeoutSecs > 0) { preparedStatement.setQueryTimeout(queryTimeoutSecs); } this.preparedStatement = preparedStatement; }
From source file:com.u2apple.rt.db.dao.DeviceDao.java
public String getMacAddressByQQ(String qq) throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet rs = null;/* ww w . jav a 2 s. c om*/ String macAddress = null; try { connection = Pool.getShuameConnection(); statement = connection.prepareStatement(GET_MAC_ADDRESS_BY_QQ); statement.setString(1, qq); statement.setQueryTimeout(Constants.TIMEOUT_LONG); rs = statement.executeQuery(); if (rs.next()) { macAddress = rs.getString("mac_address"); } } catch (JSchException | ClassNotFoundException | PropertyVetoException | IOException ex) { logger.error("SQL fail", ex); } finally { try { if (rs != null) { rs.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException ex) { logger.error("Fail when conection was closed", ex); } } return macAddress; }