Example usage for java.sql PreparedStatement setQueryTimeout

List of usage examples for java.sql PreparedStatement setQueryTimeout

Introduction

In this page you can find the example usage for java.sql PreparedStatement setQueryTimeout.

Prototype

void setQueryTimeout(int seconds) throws SQLException;

Source Link

Document

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

Usage

From source file:com.taobao.tddl.jdbc.group.TGroupPreparedStatement.java

private PreparedStatement createPreparedStatementInternal(Connection conn, String sql) throws SQLException {
    PreparedStatement ps;
    if (autoGeneratedKeys != -1) {
        ps = conn.prepareStatement(sql, autoGeneratedKeys);
    } else if (columnIndexes != null) {
        ps = conn.prepareStatement(sql, columnIndexes);
    } else if (columnNames != null) {
        ps = conn.prepareStatement(sql, columnNames);
    } else {/*from   w w w.  ja v a  2s.  c  o  m*/
        int resultSetHoldability = this.resultSetHoldability;
        if (resultSetHoldability == -1) //setResultSetHoldability
            resultSetHoldability = conn.getHoldability();

        ps = conn.prepareStatement(sql, this.resultSetType, this.resultSetConcurrency, resultSetHoldability);
    }
    setBaseStatement(ps);
    ps.setQueryTimeout(queryTimeout); //setBaseStatement
    ps.setFetchSize(fetchSize);
    ps.setMaxRows(maxRows);

    return ps;
}

From source file:com.manydesigns.portofino.actions.admin.appwizard.ApplicationWizard.java

protected void setQueryTimeout(PreparedStatement statement, int seconds) {
    try {//from  w  w w  . j av  a 2s  .c o m
        statement.setQueryTimeout(seconds);
    } catch (Exception e) {
        logger.debug("setQueryTimeout not supported", e);
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine.java

/**
 * Creates a prepared statement.//  w w  w . ja va  2s.  c  o  m
 *
 * @param name       The name of the prepared statement.
 * @param query      The query.
 * @param timeout    The timeout (in seconds) if applicable. Only applicable if > 0.
 * @param recovering True if calling from recovering, false otherwise.
 * @throws NameAlreadyExistsException If the name already exists.
 * @throws DatabaseEngineException    If something goes wrong creating the statement.
 */
private void createPreparedStatement(final String name, final String query, final int timeout,
        final boolean recovering) throws NameAlreadyExistsException, DatabaseEngineException {

    if (!recovering) {
        if (stmts.containsKey(name)) {
            throw new NameAlreadyExistsException(
                    String.format("There's already a PreparedStatement with the name '%s'", name));
        }
        try {
            getConnection();
        } catch (Exception e) {
            throw new DatabaseEngineException("Could not create prepared statement", e);
        }
    }

    PreparedStatement ps;
    try {
        ps = conn.prepareStatement(query);
        if (timeout > 0) {
            ps.setQueryTimeout(timeout);
        }
        stmts.put(name, new PreparedStatementCapsule(query, ps, timeout));
    } catch (SQLException e) {
        throw new DatabaseEngineException("Could not create prepared statement", e);
    }
}

From source file:com.hangum.tadpole.rdb.core.editors.main.composite.ResultSetComposite.java

/**
 *  ./*from w w w .  j  a v a 2  s  .  co  m*/
 * 
 * @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:nl.nn.adapterframework.jdbc.JdbcQuerySenderBase.java

protected String sendMessage(Connection connection, String correlationID, String message,
        ParameterResolutionContext prc) throws SenderException, TimeOutException {
    PreparedStatement statement = null;
    ParameterList newParamList = new ParameterList();
    if (paramList != null) {
        newParamList = (ParameterList) paramList.clone();
    }//www  .j  ava 2  s .  co  m
    if (isUseNamedParams()) {
        message = adjustParamList(newParamList, message);
    }
    try {
        boolean updateBlob = "updateBlob".equalsIgnoreCase(getQueryType());
        boolean updateClob = "updateClob".equalsIgnoreCase(getQueryType());
        log.debug(getLogPrefix() + "obtaining prepared statement to execute");
        statement = getStatement(connection, correlationID, message, updateBlob || updateClob);
        log.debug(getLogPrefix() + "obtained prepared statement to execute");
        statement.setQueryTimeout(getTimeout());
        if (prc != null && paramList != null) {
            applyParameters(statement, prc.getValues(newParamList));
        }
        if ("select".equalsIgnoreCase(getQueryType())) {
            Object blobSessionVar = null;
            Object clobSessionVar = null;
            if (prc != null && StringUtils.isNotEmpty(getBlobSessionKey())) {
                blobSessionVar = prc.getSession().get(getBlobSessionKey());
            }
            if (prc != null && StringUtils.isNotEmpty(getClobSessionKey())) {
                clobSessionVar = prc.getSession().get(getClobSessionKey());
            }
            if (isStreamResultToServlet()) {
                HttpServletResponse response = (HttpServletResponse) prc.getSession()
                        .get("restListenerServletResponse");
                String contentType = (String) prc.getSession().get("contentType");
                String contentDisposition = (String) prc.getSession().get("contentDisposition");
                return executeSelectQuery(statement, blobSessionVar, clobSessionVar, response, contentType,
                        contentDisposition);
            } else {
                return executeSelectQuery(statement, blobSessionVar, clobSessionVar);
            }
        }
        if (updateBlob) {
            if (StringUtils.isEmpty(getBlobSessionKey())) {
                return executeUpdateBlobQuery(statement, message);
            }
            return executeUpdateBlobQuery(statement,
                    prc == null ? null : prc.getSession().get(getBlobSessionKey()));
        }
        if (updateClob) {
            if (StringUtils.isEmpty(getClobSessionKey())) {
                return executeUpdateClobQuery(statement, message);
            }
            return executeUpdateClobQuery(statement,
                    prc == null ? null : prc.getSession().get(getClobSessionKey()));
        }
        if ("package".equalsIgnoreCase(getQueryType())) {
            return executePackageQuery(connection, statement, message);
        }
        return executeOtherQuery(connection, correlationID, statement, message, prc, newParamList);
    } catch (SenderException e) {
        if (e.getCause() instanceof SQLException) {
            SQLException sqle = (SQLException) e.getCause();
            if (sqle.getErrorCode() == 1013) {
                throw new TimeOutException("Timeout of [" + getTimeout() + "] sec expired");
            }
        }
        throw new SenderException(e);
    } catch (Throwable t) {
        throw new SenderException(getLogPrefix() + "got exception sending message", t);
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            log.warn(new SenderException(getLogPrefix() + "got exception closing SQL statement", e));
        }
        if (isCloseInputstreamOnExit()) {
            if (paramList != null) {
                for (int i = 0; i < paramList.size(); i++) {
                    if (Parameter.TYPE_INPUTSTREAM.equals(paramList.getParameter(i).getType())) {
                        log.debug(getLogPrefix() + "Closing inputstream for parameter ["
                                + paramList.getParameter(i).getName() + "]");
                        try {
                            InputStream inputStream = (InputStream) paramList.getParameter(i).getValue(null,
                                    prc);
                            inputStream.close();
                        } catch (Exception e) {
                            log.warn(new SenderException(getLogPrefix() + "got exception closing inputstream",
                                    e));
                        }
                    }
                }
            }
        }
    }
}

From source file:nl.nn.adapterframework.jdbc.XmlQuerySender.java

private String selectQuery(Connection connection, String correlationID, String tableName, Vector columns,
        String where, String order) throws SenderException, JdbcException {
    try {/*from w ww .jav  a  2s . c o m*/
        String query = "SELECT ";
        if (columns != null) {
            Iterator iter = columns.iterator();
            boolean firstColumn = true;
            while (iter.hasNext()) {
                Column column = (Column) iter.next();
                if (firstColumn) {
                    query = query + column.getName();
                    firstColumn = false;
                } else {
                    query = query + "," + column.getName();
                }
            }
        } else {
            query = query + "*";
        }
        query = query + " FROM " + tableName;
        if (where != null) {
            query = query + " WHERE " + where;
        }
        if (order != null) {
            query = query + " ORDER BY " + order;
        }
        PreparedStatement statement = getStatement(connection, correlationID, query, false);
        statement.setQueryTimeout(getTimeout());
        setBlobSmartGet(true);
        return executeSelectQuery(statement, null, null);
    } catch (SQLException e) {
        throw new SenderException(getLogPrefix() + "got exception executing a SELECT SQL command", e);
    }
}

From source file:nl.nn.adapterframework.jdbc.XmlQuerySender.java

private String deleteQuery(Connection connection, String correlationID, String tableName, String where)
        throws SenderException, JdbcException {
    try {//from ww  w  . j  av  a2  s  .  c om
        String query = "DELETE FROM " + tableName;
        if (where != null) {
            query = query + " WHERE " + where;
        }
        PreparedStatement statement = getStatement(connection, correlationID, query, false);
        statement.setQueryTimeout(getTimeout());
        return executeOtherQuery(connection, correlationID, statement, query, null, null);
    } catch (SQLException e) {
        throw new SenderException(getLogPrefix() + "got exception executing a DELETE SQL command", e);
    }
}

From source file:nl.nn.adapterframework.jdbc.XmlQuerySender.java

private String sql(Connection connection, String correlationID, String query, String type)
        throws SenderException, JdbcException {
    try {//from   w w  w.  ja  v  a  2 s. c  o m
        PreparedStatement statement = getStatement(connection, correlationID, query, false);
        statement.setQueryTimeout(getTimeout());
        setBlobSmartGet(true);
        if (StringUtils.isNotEmpty(type) && type.equalsIgnoreCase("select")) {
            return executeSelectQuery(statement, null, null);
        } else if (StringUtils.isNotEmpty(type) && type.equalsIgnoreCase("ddl")) {
            //TODO: alles tussen -- en newline nog weggooien
            StringBuffer result = new StringBuffer();
            StringTokenizer stringTokenizer = new StringTokenizer(query, ";");
            while (stringTokenizer.hasMoreTokens()) {
                String q = stringTokenizer.nextToken();
                statement = getStatement(connection, correlationID, q, false);
                if (q.trim().toLowerCase().startsWith("select")) {
                    result.append(executeSelectQuery(statement, null, null));
                } else {
                    result.append(executeOtherQuery(connection, correlationID, statement, q, null, null));
                }
            }
            return result.toString();
        } else {
            return executeOtherQuery(connection, correlationID, statement, query, null, null);
        }
    } catch (SQLException e) {
        throw new SenderException(getLogPrefix() + "got exception executing a SQL command", e);
    }
}

From source file:nl.nn.adapterframework.jdbc.XmlQuerySender.java

private String executeUpdate(Connection connection, String correlationID, String tableName, String query,
        Vector columns) throws SenderException {
    try {/*from   www.  j  a v a 2s  .c  o m*/
        if (existLob(columns)) {
            CallableStatement callableStatement = getCallWithRowIdReturned(connection, correlationID, query);
            applyParameters(callableStatement, columns);
            int ri = 1 + countParameters(columns);
            callableStatement.registerOutParameter(ri, Types.VARCHAR);
            callableStatement.setQueryTimeout(getTimeout());
            int numRowsAffected = callableStatement.executeUpdate();
            String rowId = callableStatement.getString(ri);
            log.debug(getLogPrefix() + "returning ROWID [" + rowId + "]");

            Iterator iter = columns.iterator();
            while (iter.hasNext()) {
                Column column = (Column) iter.next();
                if (column.getType().equalsIgnoreCase(TYPE_BLOB)
                        || column.getType().equalsIgnoreCase(TYPE_CLOB)) {
                    query = "SELECT " + column.getName() + " FROM " + tableName + " WHERE ROWID=?"
                            + " FOR UPDATE";
                    PreparedStatement statement = getStatement(connection, correlationID, query, true);
                    statement.setString(1, rowId);
                    statement.setQueryTimeout(getTimeout());
                    if (column.getType().equalsIgnoreCase(TYPE_BLOB)) {
                        executeUpdateBlobQuery(statement, column.getValue());
                    } else {
                        executeUpdateClobQuery(statement, column.getValue());
                    }
                }
            }
            return "<result><rowsupdated>" + numRowsAffected + "</rowsupdated></result>";
        }
        PreparedStatement statement = getStatement(connection, correlationID, query, false);
        applyParameters(statement, columns);
        statement.setQueryTimeout(getTimeout());
        return executeOtherQuery(connection, correlationID, statement, query, null, null);
    } catch (Throwable t) {
        throw new SenderException(t);
    }
}

From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java

private PreparedStatement getPreparedStatement(Connection conn, boolean callable) throws SQLException {
    Map<String, PreparedStatement> preparedStatementMap = perConnCache.get(conn);
    if (null == preparedStatementMap) {
        @SuppressWarnings("unchecked") // LRUMap is not generic
        Map<String, PreparedStatement> lruMap = new LRUMap(MAX_OPEN_PREPARED_STATEMENTS) {
            private static final long serialVersionUID = 1L;

            @Override/*from   w w  w  . jav a 2 s. co  m*/
            protected boolean removeLRU(LinkEntry entry) {
                PreparedStatement preparedStatement = (PreparedStatement) entry.getValue();
                close(preparedStatement);
                return true;
            }
        };
        preparedStatementMap = Collections.<String, PreparedStatement>synchronizedMap(lruMap);
        // As a connection is held by only one thread, we cannot already have a 
        // preparedStatementMap put by another thread
        perConnCache.put(conn, preparedStatementMap);
    }
    PreparedStatement pstmt = preparedStatementMap.get(getQuery());
    if (null == pstmt) {
        if (callable) {
            pstmt = conn.prepareCall(getQuery());
        } else {
            pstmt = conn.prepareStatement(getQuery());
        }
        pstmt.setQueryTimeout(getIntegerQueryTimeout());
        // PreparedStatementMap is associated to one connection so 
        //  2 threads cannot use the same PreparedStatement map at the same time
        preparedStatementMap.put(getQuery(), pstmt);
    } else {
        int timeoutInS = getIntegerQueryTimeout();
        if (pstmt.getQueryTimeout() != timeoutInS) {
            pstmt.setQueryTimeout(getIntegerQueryTimeout());
        }
    }
    pstmt.clearParameters();
    return pstmt;
}