我如何检测事务是否保持打开状态,是否仍等待 JDBC 上的 COMMIT
或 ROLLBACK
Connection ?
我通过连接池获取连接对象。所以我想在使用之前检查连接的状态。
使用 Postgres 9.x 和 Java 8。
最佳答案
我不知道有什么方法可以仅使用标准 JDBC API 方法来检测 Connection
上的当前事务状态。
但是,对于 PostgreSQL 特别是,有 AbstractJdbc2Connection.getTransactionState()
,您可以将其与常量 ProtocolConnection.TRANSACTION_IDLE
进行比较. PostgreSQL 的 JDBC4 Connection
扩展了这个类,所以你应该能够转换你的 Connection
来访问这个属性。
该常量是 pgjdbc
驱动程序中定义的三个值之一 source code :
/**
* Constant returned by {@link #getTransactionState} indicating that no
* transaction is currently open.
*/
static final int TRANSACTION_IDLE = 0;
/**
* Constant returned by {@link #getTransactionState} indicating that a
* transaction is currently open.
*/
static final int TRANSACTION_OPEN = 1;
/**
* Constant returned by {@link #getTransactionState} indicating that a
* transaction is currently open, but it has seen errors and will
* refuse subsequent queries until a ROLLBACK.
*/
static final int TRANSACTION_FAILED = 2;
关于java - 检测 JDBC 连接中尚未提交的打开事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754214/