2

I have an SQL query executed by:

ResultSet resultSet = preparedStatement.executeQuery();

while( resultSet.next() ){
     // do some stuff
}

Is there a way to stop the execution and do some code after let's say 2 minutes of execution?

Thanks

daiquiri33
  • 65
  • 2
  • 7

1 Answers1

2

You can set a timeout on executing a query. SQLException will be thrown if the query doesn't complete in time and times out:

preparedstatement.setQueryTimeout(seconds);
ResultSet resultSet = preparedStatement.executeQuery();

while( resultSet.next() ){
     // do some stuff
}

Have a look at setQueryTimeout documentation

Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • Will that actually "stop execution" of the query though (this seems to be what daiquiri33 is asking for)? I would guess this depends heavily on the backing database, which may or may not support time limits attached to a query? – us2012 Jan 02 '13 at 13:24
  • Thanks guys ! Stopping the execution would be perfect for the good health of the database, but this will definitively unlock me for now. Happy New Year ! – daiquiri33 Jan 02 '13 at 13:28
  • @us2012 You are right in saying that it depends on the underlying DB, however most (if not all) databases support timeout on queries. In any case, Java process would abort the call and throw the SQLException – Aleks G Jan 02 '13 at 13:28