Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I abort a running JDBC transaction?

Tags:

java

jdbc

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?

like image 927
Aaron Digulla Avatar asked Nov 17 '08 15:11

Aaron Digulla


People also ask

Which methods can be used in JDBC to abort a transaction and restore the values to what they were before the attempted update?

After inserting the outdated prices, the employee realizes that they are no longer valid and calls the Connection method rollback to undo their effects. (The method rollback aborts a transaction and restores values to what they were before the attempted update.)

How can you avoid auto commit mode in JDBC?

Explicit Transaction Management When Auto-Commit Is False We need to disable auto-commit mode when we want to handle transactions ourselves and group multiple SQL statements into one transaction. We do this by passing false to the connection's setAutoCommit method: connection. setAutoCommit(false);


1 Answers

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

like image 125
John M Avatar answered Sep 21 '22 05:09

John M