当前位置: 首页>>代码示例>>Java>>正文


Java Statement.setQueryTimeout方法代码示例

本文整理汇总了Java中java.sql.Statement.setQueryTimeout方法的典型用法代码示例。如果您正苦于以下问题:Java Statement.setQueryTimeout方法的具体用法?Java Statement.setQueryTimeout怎么用?Java Statement.setQueryTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.sql.Statement的用法示例。


在下文中一共展示了Statement.setQueryTimeout方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testBug22359

import java.sql.Statement; //导入方法依赖的package包/类
/**
 * Tests fix for BUG#22359 - Driver was using millis for
 * Statement.setQueryTimeout() when spec says argument is seconds.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug22359() throws Exception {
    if (versionMeetsMinimum(5, 0)) {
        Statement timeoutStmt = null;

        try {
            timeoutStmt = this.conn.createStatement();
            timeoutStmt.setQueryTimeout(2);

            long begin = System.currentTimeMillis();

            try {
                timeoutStmt.execute("SELECT SLEEP(30)");
                fail("Query didn't time out");
            } catch (MySQLTimeoutException timeoutEx) {
                long end = System.currentTimeMillis();

                assertTrue((end - begin) > 1000);
            }
        } finally {
            if (timeoutStmt != null) {
                timeoutStmt.close();
            }
        }
    }
}
 
开发者ID:JuanJoseFJ,项目名称:ProyectoPacientes,代码行数:33,代码来源:StatementRegressionTest.java

示例2: readAnswers

import java.sql.Statement; //导入方法依赖的package包/类
private List<Answer> readAnswers(int questionDataBaseId, Connection connection) throws SQLException {
	Statement statement = connection.createStatement();
	statement.setQueryTimeout(10);
	List<Answer> answers = new ArrayList<Answer>();

	ResultSet answerSet = statement
			.executeQuery("SELECT answerid, answertext  " + "FROM answer WHERE questionid=" + questionDataBaseId);
	while (answerSet.next()) {
		int awId = answerSet.getInt("answerid");
		String awText = answerSet.getString("answertext");
		answers.add(new Answer(this,awId, awText));

	}
	if (answers.size() == 0) {
		answers.add(new Answer(this,-1, "Richtig"));
		answers.add(new Answer(this,-2, "Falsch"));
	}
	return answers;
}
 
开发者ID:argo2445,项目名称:QBot,代码行数:20,代码来源:Question.java

示例3: executeLockWithStatement

import java.sql.Statement; //导入方法依赖的package包/类
private static void executeLockWithStatement(IPersistent object, DataSource dataSource)
throws SQLException, IllegalAccessException, InvocationTargetException, IOException {
    String sql = StatementHelper.getLockStatementString(object, dataSource.getEngineType());
    Statement statement = dataSource.getStatement();
    // Added for MS-Sql-Server as 'NO-WAIT" is not implemented like in Oracle
    statement.setQueryTimeout(QUERY_TIMEOUT_FOR_LOCKING);
    if (log.isInfoEnabled()) {
        log.info("Executing the SQL\n" + sql);
        long currentTimeMillis = System.currentTimeMillis();
        statement.execute(sql);
        log.info("Elapsed:" + (System.currentTimeMillis() - currentTimeMillis));
    } else {
        statement.execute(sql);
    }
    dataSource.closeStatement(statement);
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:17,代码来源:JdbcBridge.java

示例4: isValid

import java.sql.Statement; //导入方法依赖的package包/类
@Override
public boolean isValid(int timeout) throws SQLException
{
	if (isClosed())
		return false;
	Statement statement = createStatement();
	statement.setQueryTimeout(timeout);
	try (ResultSet rs = statement.executeQuery("SELECT 1"))
	{
		if (rs.next())
			return true;
	}
	return false;
}
 
开发者ID:olavloite,项目名称:spanner-jdbc,代码行数:15,代码来源:CloudSpannerConnection.java

示例5: createStatement

import java.sql.Statement; //导入方法依赖的package包/类
@Override
public Object createStatement(Object proxy, Method method, Object[] args, Object statement, long time) {
    if (statement instanceof Statement && timeout > 0) {
        Statement s = (Statement)statement;
        try {
            s.setQueryTimeout(timeout);
        }catch (SQLException x) {
            log.warn("[QueryTimeoutInterceptor] Unable to set query timeout:"+x.getMessage(),x);
        }
    }
    return statement;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:13,代码来源:QueryTimeoutInterceptor.java

示例6: testLongValidationQueryTime

import java.sql.Statement; //导入方法依赖的package包/类
@Test
public void testLongValidationQueryTime() throws Exception {
    // use our mock driver
    this.datasource.setDriverClassName("org.h2.Driver");
    this.datasource.setUrl("jdbc:h2:~/.h2/test;QUERY_TIMEOUT=0;DB_CLOSE_ON_EXIT=FALSE");
    Connection con = this.datasource.getConnection();
    Statement stmt = null;
    long start = 0, end = 0;
    try {
        stmt = con.createStatement();
        // set the query timeout to 2 sec
        //  this keeps this test from slowing things down too much
        stmt.setQueryTimeout(2);
        // assert that our long query takes longer than one second to run
        //  this is a requirement for other tests to run properly
        start = System.currentTimeMillis();
        stmt.execute(longQuery);
    } catch (SQLException ex) {}
    finally {
        end = System.currentTimeMillis();

        if (stmt != null) { stmt.close(); }
        if (con != null) { con.close(); }

        Assert.assertTrue(start != 0 && end != 0);
        Assert.assertTrue((end - start) > 1000);
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:29,代码来源:TestValidationQueryTimeout.java

示例7: applyTimeout

import java.sql.Statement; //导入方法依赖的package包/类
/**
 * Apply the specified timeout - overridden by the current transaction timeout,
 * if any - to the given JDBC Statement object.
 * @param stmt the JDBC Statement object
 * @param dataSource the DataSource that the Connection was obtained from
 * @param timeout the timeout to apply (or 0 for no timeout outside of a transaction)
 * @throws SQLException if thrown by JDBC methods
 * @see java.sql.Statement#setQueryTimeout
 */
public static void applyTimeout(Statement stmt, DataSource dataSource, int timeout) throws SQLException {
	Assert.notNull(stmt, "No Statement specified");
	Assert.notNull(dataSource, "No DataSource specified");
	ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
	if (holder != null && holder.hasTimeout()) {
		// Remaining transaction timeout overrides specified value.
		stmt.setQueryTimeout(holder.getTimeToLiveInSeconds());
	}
	else if (timeout > 0) {
		// No current transaction timeout -> apply specified value.
		stmt.setQueryTimeout(timeout);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:DataSourceUtils.java

示例8: readCategories

import java.sql.Statement; //导入方法依赖的package包/类
/**
 * @param connection
 * @throws SQLException
 */
private void readCategories(Connection connection) throws SQLException {
	Statement statement = connection.createStatement();
	statement.setQueryTimeout(10);
	categories = new ArrayList<>();
	ResultSet rs = statement.executeQuery("SELECT categoryid, description FROM category");
	while (rs.next()) {
		int categorieId = rs.getInt("categoryid");
		String description = rs.getString("description");
		// Check if category already exists
		if (categories.stream().filter(elem -> elem.getDatabaseID() == categorieId).count() == 0) {
			categories.add(new Category(categorieId, description));
		}
	}
}
 
开发者ID:argo2445,项目名称:QBot,代码行数:19,代码来源:Question.java

示例9: executeQuery

import java.sql.Statement; //导入方法依赖的package包/类
/** Executes a query against the underlying data source. Returns a Collection of persistent objects.
 * The Statement object that is internally used for executing the query, will be automatically closed, once the recordset has been completely traversed.
 * @param sql The query to execute.
 * @param classMetaData The ClassMetaData defintion to be used for molding the ResultSet into Persistent objects.
 * @param criteria The Criteria used for the query. This will provide the values to set the various flags on the Persistent object.
 * @param queryTimeout This will be used for setting the timeout value on the Statement object; zero means there is no limit.
 * @param pagingPlugin The IPagingPlugin implementation that may be used to return a page of Results.
 * @throws SQLException if any database error occurs.
 * @throws PostLoadFailedException if any error is thrown in the PostLoad trigger of the persistent object.
 * @throws DataSourceCursorRuntimeException if any error occurs while molding the row into the Persistent object.
 * @throws IOException if any error occurs in reading the data from the database.
 * @return a Collection of persistent objects.
 */
public Collection executeQuery(String sql, ClassMetaData classMetaData, Criteria criteria, int queryTimeout, IPagingPlugin pagingPlugin)
throws SQLException, PostLoadFailedException, DataSourceCursorRuntimeException, IOException {
    Statement statement = getStatement();

    // The following sets the timeout; zero means there is no limit
    // The setting works in MS-Sql-Server only !!
    statement.setQueryTimeout(queryTimeout);

    // set the fetch size
    try {
        statement.setFetchSize(getHitlistSize().intValue());
    } catch (Throwable e) {
        // NOTE: The setFetchSize feature may not be implemented by all the drivers. eg.Postgresql.
        // so just ignore the exception
    }
    ResultSet resultSet = null;
    if (log.isInfoEnabled()) {
        log.info("Executing the SQL:\n" + sql);
        long currentTimeMillis = System.currentTimeMillis();
        resultSet = statement.executeQuery(sql);
        log.info("Elapsed:" + (System.currentTimeMillis() - currentTimeMillis));
    } else {
        resultSet = statement.executeQuery(sql);
    }
    registerStatement(statement, resultSet);
    return new DataSourceCursor(this, statement, resultSet, classMetaData, criteria, pagingPlugin);
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:41,代码来源:DataSource.java

示例10: validate

import java.sql.Statement; //导入方法依赖的package包/类
/**
 * Validates a connection.
 * @param validateAction the action used. One of {@link #VALIDATE_BORROW}, {@link #VALIDATE_IDLE},
 * {@link #VALIDATE_INIT} or {@link #VALIDATE_RETURN}
 * @param sql the SQL to be used during validation. If the {@link PoolConfiguration#setInitSQL(String)} has been called with a non null
 * value and the action is {@link #VALIDATE_INIT} the init SQL will be used for validation.
 *
 * @return true if the connection was validated successfully. It returns true even if validation was not performed, such as when
 * {@link PoolConfiguration#setValidationInterval(long)} has been called with a positive value.
 * <p>
 * false if the validation failed. The caller should close the connection if false is returned since a session could have been left in
 * an unknown state during initialization.
 */
public boolean validate(int validateAction,String sql) {
    if (this.isDiscarded()) {
        return false;
    }

    if (!doValidate(validateAction)) {
        //no validation required, no init sql and props not set
        return true;
    }

    //Don't bother validating if already have recently enough
    long now = System.currentTimeMillis();
    if (validateAction!=VALIDATE_INIT &&
        poolProperties.getValidationInterval() > 0 &&
        (now - this.lastValidated) <
        poolProperties.getValidationInterval()) {
        return true;
    }

    if (poolProperties.getValidator() != null) {
        if (poolProperties.getValidator().validate(connection, validateAction)) {
            this.lastValidated = now;
            return true;
        } else {
            if (getPoolProperties().getLogValidationErrors()) {
                log.error("Custom validation through "+poolProperties.getValidator()+" failed.");
            }
            return false;
        }
    }

    String query = sql;

    if (validateAction == VALIDATE_INIT && poolProperties.getInitSQL() != null) {
        query = poolProperties.getInitSQL();
    }

    if (query == null) {
        query = poolProperties.getValidationQuery();
    }

    Statement stmt = null;
    try {
        stmt = connection.createStatement();

        int validationQueryTimeout = poolProperties.getValidationQueryTimeout();
        if (validationQueryTimeout > 0) {
            stmt.setQueryTimeout(validationQueryTimeout);
        }

        stmt.execute(query);
        stmt.close();
        this.lastValidated = now;
        return true;
    } catch (Exception ex) {
        if (getPoolProperties().getLogValidationErrors()) {
            log.warn("SQL Validation error", ex);
        } else if (log.isDebugEnabled()) {
            log.debug("Unable to validate object:",ex);
        }
        if (stmt!=null)
            try { stmt.close();} catch (Exception ignore2){/*NOOP*/}
    }
    return false;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:79,代码来源:PooledConnection.java

示例11: Question

import java.sql.Statement; //导入方法依赖的package包/类
/**
 * @param questionDatabaseID
 *            QuestionId used in Database
 * @throws SQLException
 */
public Question(int questionDatabaseID) {
	Connection connection = null;
	try {
		connection = DriverManager.getConnection("jdbc:sqlite:" + QuizController.DB_PATH);

		if (categories == null) {
			readCategories(connection);
		}
		// categories exist
		Statement statement = connection.createStatement();
		statement.setQueryTimeout(10);
		ResultSet resultSet = statement.executeQuery("SELECT "
				+ "questionid, questiontext, istrue, askedquestions, rightansweredquestions, categoryid, rightanswerid "
				+ "FROM question WHERE questionid=" + questionDatabaseID);

		if (resultSet.next()) {
			this.questionText = resultSet.getString("questiontext");
			this.isTrue = resultSet.getBoolean("istrue");
			this.rightAnswered = resultSet.getInt("rightansweredquestions");
			this.answered = resultSet.getInt("askedquestions");
			this.dataBaseId = resultSet.getInt("questionid");
			this.answers = readAnswers(dataBaseId, connection);
			if (this.answers.size() > 0) {
				int rightAnswerId = resultSet.getInt("rightanswerid");
				if (rightAnswerId == 0) {
					// Entscheidungsfrage
					if (isTrue) {
						rightAnswer = answers.get(0);
					} else {
						rightAnswer = answers.get(1);
					}
				} else {
					// keine Entscheidungsfrage
					Optional<Answer> optRightAnswer = answers.stream()
							.filter(aw -> aw.getDatabaseId() == rightAnswerId).findFirst();
					if (optRightAnswer.isPresent())
						this.rightAnswer = optRightAnswer.get();
					else {
						throw new IllegalArgumentException(
								"Die korrekte Antwort für " + this.dataBaseId + " konnte nicht gefunden werden.");
					}
				}
			}
			int categoryKey = resultSet.getInt("categoryid");
			Optional<Category> categ = categories.stream().filter(cat -> cat.getDatabaseID() == categoryKey)
					.findFirst();
			if (categ.isPresent()) {
				this.category = categ.get();
			} else {
				throw new IllegalArgumentException(
						"Die Kategorie mit dem Schlüssel " + categoryKey + " existiert nicht.");
			}

		}
		connection.close();
	} catch (Exception e) {
		e.printStackTrace(System.err);
	}
}
 
开发者ID:argo2445,项目名称:QBot,代码行数:65,代码来源:Question.java

示例12: createDB

import java.sql.Statement; //导入方法依赖的package包/类
private static void createDB(Connection con) throws SQLException {
	logger.info("Create Database..");
	
	Statement stmt = con.createStatement();
	stmt.setQueryTimeout(30);  // set timeout to 30 sec.

	// create library description table
	String sql = "CREATE TABLE IF NOT EXISTS " + T_LIBRARY +  "(" +
		COL_ID + " INTEGER, " +
		COL_NAME + " VARCHAR(255) not NULL, " +         // library name
		COL_CATEGORY + " VARCHAR(255) not NULL, " +     // one of:  Advertising, Analytics, Android, Tracker, SocialMedia, Cloud, Utilities
		COL_VERSION + " VARCHAR(255) not NULL, " +      // library version
		COL_RELEASEDATE + " INTEGER not NULL, " +       // long milliseconds since beginning
		COL_LIB_PACKAGES + " INTEGER not NULL, " +      // number of non-empty lib packages
		COL_LIB_CLASSES + " INTEGER not NULL, " +       // number of lib classes
		COL_LIB_METHODS + " INTEGER, " +                // number of lib methods
		COL_ROOT_PACKAGE + " VARCHAR(255), " +          // library root package, might be null if ambigious
		"PRIMARY KEY (" + COL_NAME + ", " + COL_VERSION + ")"
	+ ")";
	stmt.executeUpdate(sql);
	
	// create application stats table
	sql = "CREATE TABLE IF NOT EXISTS " + T_APPLICATION +  "(" +
		COL_ID + " INTEGER, " +
		COL_NAME + " VARCHAR(255) not NULL, " +        // package name
		COL_VERSION + " INTEGER not NULL, " +          // version code
		COL_SHAREDUID + " VARCHAR(255), " +            // shared uid
		COL_PROCESSING_TIME + " INTEGER not NULL, " +  // processing time in ms
		COL_APP_PACKAGES + " INTEGER not NULL, " +     // number of non-empty app packages
		COL_APP_CLASSES + " INTEGER not NULL, " +      // number of app classes
		COL_RELEASEDATE + " INTEGER, " +       		   // long milliseconds since beginning
		"PRIMARY KEY (" + COL_NAME + ", " + COL_VERSION + ")"
	+ ")";
	stmt.executeUpdate(sql);	

	// create profile match table
	sql = "CREATE TABLE IF NOT EXISTS " + T_PROFILE +  "(" +
		COL_ID + " INTEGER PRIMARY KEY, " +                 
		COL_LIBID + " INTEGER NOT NULL, " +               // Reference to T_LIBRARY.COL_ID
		COL_APPID + " INTEGER NOT NULL, " +               // Reference to T_APPLICATION.COL_ID
		COL_ISOBFUSCATED + " INTEGER NOT NULL, " +        // boolean, either 0 or 1
		COL_ROOTPCKG_PRESENT  + " INTEGER NOT NULL, " +   // boolean, either 0 or 1
		COL_MATCHLEVEL + " INTEGER NOT NULL, " +          // see SerializableProfileMatch.matchLevel
		COL_SIMSCORE + " REAL "                           // similarity score between [0..1]
	+ ")";
	stmt.executeUpdate(sql);
	
	// create naive package name match table
	sql = "CREATE TABLE IF NOT EXISTS " + T_PACKAGE_MATCH +  "(" +
		COL_APPID + " INTEGER NOT NULL, " +                 // Reference to T_APPLICATION.COL_ID
		COL_LIBNAME + " VARCHAR(255) NOT NULL, " +          // library name
		"PRIMARY KEY (" + COL_APPID + ", " + COL_LIBNAME + ")"
	+ ")";
	stmt.executeUpdate(sql);

	// create library api usage table
	sql = "CREATE TABLE IF NOT EXISTS " + T_LIBUSAGE +  "(" +
		COL_PROFILEID + " INTEGER NOT NULL, " +             // Reference to T_PROFILE.COL_ID
		COL_API + " VARCHAR(255) NOT NULL, " +              // api signature
		"PRIMARY KEY (" + COL_PROFILEID + ", " + COL_API + ")"
	+ ")";
	stmt.executeUpdate(sql);

}
 
开发者ID:reddr,项目名称:LibScout,代码行数:65,代码来源:SQLStats.java


注:本文中的java.sql.Statement.setQueryTimeout方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。