tags:

views:

925

answers:

4

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 define a way to send a "stop whatever you are doing on this connection" signal to the DB?

A: 

No, you can't abort it using standard JDBC.

You might try to check if your particular RDBMS define some extension to suppot it.

Dev er dev
I've had vendors tell me this. If a particular JDBC driver doesn't implement Statement.cancel(), that's a quality-of-implementation problem. It's there and documented for that use case.
John M
+6  A: 

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).

Gowri
+3  A: 

Check out Statement.cancel().

james
+6  A: 

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).

John M