简体   繁体   English

如何中止正在运行的JDBC事务?

[英]How can I abort a running JDBC transaction?

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是否定义了一种方法来向数据库发送“停止在此连接上执行的任何操作”信号?

As mentioned by james, Statement.cancel() will cancel the execution of a running Statement (select, update, etc). 正如james所提到的, Statement.cancel()将取消正在运行的Statement(select,update等)的执行。 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. JDBC文档特别指出Statement.cancel()从另一个线程运行是安全的,甚至建议在超时线程中调用它。

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. Connection.rollback()应该在执行所有其他JDBC调用的主线程中发生。 You can handle that after the canceled Statement.execute...() call completes with a JDBCException (due to the cancel). 在取消的Statement.execute ...()调用以JDBCException(由于取消)完成后,您可以处理该问题。

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. 为此,JDBC支持查询超时的概念。 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()). 并且通过回滚事务来处理execute()方法抛出的SQLException (当然,这只有在autocommit设置为false且JDBC驱动程序支持Statement.cancel()时才有效)。

查看Statement.cancel()。

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是否定义了一些扩展来支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM