简体   繁体   English

如何故意延迟jdbc prepareStatement的executeQuery()?

[英]How to delay executeQuery() of jdbc preparedStatement intentionally?

It is mentioned in the Java API docs that Statement interface has setQueryTimeOut method. Java API文档中提到Statement接口具有setQueryTimeOut方法。 And I did use it with PreparedStatement. 我确实将它与PreparedStatement一起使用。 Now unfortunately I am not able to confirm that it is indeed working. 现在不幸的是,我无法确认它确实在工作。 I have set it to 1s which is minimum like below: 我将其设置为1s,这是最小值,如下所示:

pstmt = connection.prepareStatement(sqlQuery);
pstmt.setString(1, age);
pstmt.setQueryTimeout(1);
resultSet = pstmt.executeQuery();

Query is simple Select query from a view based on age. 查询很简单根据年龄从视图中选择查询。 But Db response has become better and execution of query is getting completed within 500ms. 但是Db响应变得更好,并且查询的执行已在500毫秒内完成。 How to intentionally delay the execution of query so that SQLException which will be thrown by setQueryTimeOut method will be caught? 如何有意地延迟查询的执行,以便捕获由setQueryTimeOut方法抛出的SQLException?

You can pause via TimeUnit class which is java.util.concurrent package . 您可以通过TimeUnit类(它是java.util.concurrent package暂停。

TimeUnit.SECONDS.sleep(1);

To sleep for one second or 睡一秒钟或

TimeUnit.MINUTES.sleep(1);

To sleep for a minute. 睡一分钟。

Implement in this way 以这种方式实施

pstmt = connection.prepareStatement(sqlQuery);
pstmt.setString(1, age);
TimeUnit.MINUTES.sleep(1);
resultSet = pstmt.executeQuery();

On a fine note sleep method throws InterruptedException exception so you have to take care of that. 值得注意的是,sleep方法会引发InterruptedException异常,因此您必须注意这一点。

Also if you don't want an overhead of TimeUnit class just simply call Thead.sleep(long) in your code in below manner. 同样,如果您不想占用TimeUnit的开销,则只需按照以下方式在代码中调用Thead.sleep(long)。

pstmt = connection.prepareStatement(sqlQuery);
pstmt.setString(1, age);
Thread.sleep(60);
resultSet = pstmt.executeQuery();

But again you have to take care of InterruptedException which sleep method throws. 但是同样,您必须照顾睡眠方法抛出的InterruptedException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM