JDBC确定活动事务

时间:2014-10-30 12:08:11

标签: java jdbc

这是用JDBC确定我没有提交活动事务的方法吗? 我想确保在Connection.close()之前提交或回滚所有事务。

2 个答案:

答案 0 :(得分:1)

没有标准的JDBC方法可以做你想要的。但是如果你想确保在Connection.close()之前提交/回滚所有事务,你可以这样做:

Connection conn = null;

try {
    conn = ...;
    conn.setAutoCommit(false);

    // do stuff

    // commit only if everything is successful
    conn.commit();
}
catch (SomeException e) {
    // log exceptions
}
finally {
    if (conn != null) {
        /* ALWAYS rollback before closing the connection
         * if there's any caught/uncaught exception, the transaction will be rolled back
         * if everything is successful / commit is successful, the rollback will have no effect
         */
        try {
            conn.rollback();
        }
        catch (SQLException e) {}

        try {
            conn.close();
        }
        catch (SQLException e) {}
    }
}

这比仅在存在异常(在catch块中)回滚更好,因为,如果有任何未捕获的异常:

  • 不会调用rollback()
  • 在存在活动事务时将调用Connection.close(),并且活动事务发生的情况是特定于实现的。见Bogdan Calmac's answer

答案 1 :(得分:0)

您可以查看Oracle提供的V$TRANSACTION视图。

SELECT
   s.osuser, vp.spid as os_pid, S.BLOCKING_SESSION blocker,
   S.SID, S.SERIAL#, S.USERNAME, S.MACHINE,
   Q.SQL_FULLTEXT cur_sql, PQ.SQL_FULLTEXT prev_sql, 
   vt.used_urec, vt.start_date
FROM 
   v$session S
   LEFT JOIN v$sqlarea Q on S.SQL_ID = Q.SQL_ID
   LEFT JOIN v$sqlarea PQ on S.PREV_SQL_ID = PQ.SQL_ID
   LEFT JOIN v$process vp on s.paddr = vp.addr
   LEFT JOIN v$transaction vt on s.saddr = vt.ses_addr
WHERE
   vt.start_date < SYSDATE - (5/1440)
--   AND
--   s.machine = 'machine.name'
ORDER BY 
   S.SID
; 

查询来源:What I Learned Today