Is there a way to prematurely abort a transaction? Say, I have sent a command to the database which runs five minutes and after four, I want to abort it.
Does JDBC d
Check out Statement.cancel().
As mentioned by james, Statement.cancel() will cancel the execution of a running Statement (select, update, etc). The JDBC docs specifically say that Statement.cancel() is safe to run from another thread and even suggests the usage of calling it in a timeout thread.
After canceling the statement, you're still stuck with the job of rolling back the transaction. That is not documented as being safe to run from another thread. The Connection.rollback() should happen in the main thread doing all the other JDBC calls. You can handle that after the canceled Statement.execute...() call completes with a JDBCException (due to the cancel).
I am guessing what you want to do is prevent your application blocking on long running queries / transactions. To this end, JDBC supports the concept of a query time out. You can set the query timeout using this:
java.sql.Statement.setQueryTimeout(seconds)
And handle the SQLException
thrown by the execute()
method by rolling back the transaction (of course, that would only work if you have autocommit set to false, and your JDBC driver supports Statement.cancel()).
No, you can't abort it using standard JDBC.
You might try to check if your particular RDBMS define some extension to suppot it.