java - 关闭数据库连接之前为什么要先设置自动提交为true?

查看:133
本文介绍了java - 关闭数据库连接之前为什么要先设置自动提交为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

public void close() throws SQLException {
    if (connection != null) {
      resetAutoCommit();
      if (log.isDebugEnabled()) {
        log.debug("Closing JDBC Connection [" + connection + "]");
      }
      connection.close();
    }
  }

上面是mybatis中的JdbcTransaction中的close方法, resetAutoCommit()方法是设置autoCommit=true。
为什么在关闭连接的时候要先设置自动提交为true。

解决方案


    protected void resetAutoCommit() {
        try {
          if (!connection.getAutoCommit()) {
            // MyBatis does not call commit/rollback on a connection if just selects were performed.
            // Some databases start transactions with select statements
            // and they mandate a commit/rollback before closing the connection.
            // A workaround is setting the autocommit to true before closing the connection.
            // Sybase throws an exception here.
            if (log.isDebugEnabled()) {
              log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
            }
            connection.setAutoCommit(true);
          }
        } catch (SQLException e) {
          log.debug("Error resetting autocommit to true "
              + "before closing the connection.  Cause: " + e);
        }
      }

代码中已经明确的说明了。那段注释。

这篇关于java - 关闭数据库连接之前为什么要先设置自动提交为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆