Java 如何中止正在运行的 JDBC 事务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/295920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I abort a running JDBC transaction?
提问by Aaron Digulla
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?
JDBC 是否定义了一种向数据库发送“停止您在此连接上所做的一切”信号的方法?
采纳答案by John M
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.
正如 james 所提到的,Statement.cancel()将取消正在运行的 Statement(选择、更新等)的执行。JDBC 文档特别指出 Statement.cancel() 从另一个线程运行是安全的,甚至建议在超时线程中调用它的用法。
After canceling the statement, you're still stuck with the job of rolling back the transaction. That is notdocumented 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).
取消语句后,您仍然坚持回滚事务的工作。这没有记录为从另一个线程运行是安全的。该Connection.rollback()应该在主线程中完成所有其他JDBC调用发生。您可以在取消的 Statement.execute...() 调用以 JDBCException (由于取消)完成后处理该问题。
回答by Marko
No, you can't abort it using standard JDBC.
不,您不能使用标准 JDBC 中止它。
You might try to check if your particular RDBMS define some extension to suppot it.
您可能会尝试检查您的特定 RDBMS 是否定义了一些扩展来支持它。
回答by Gowri
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:
我猜您想要做的是防止您的应用程序阻塞长时间运行的查询/事务。为此,JDBC 支持查询超时的概念。您可以使用以下方法设置查询超时:
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()).
并通过回滚事务来处理方法SQLException
抛出的问题execute()
(当然,这只有在您将 autocommit 设置为 false 并且您的 JDBC 驱动程序支持 Statement.cancel() 时才有效)。
回答by james
Check out Statement.cancel().
查看 Statement.cancel()。