⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqltransaction.java

📁 JAVA编程百例书中各章节的所有例子的源代码,包括套接字编程
💻 JAVA
字号:
package ch03.section07;

import java.sql.*;

public class SQLTransaction {

  public Connection conn = null;
  public Statement stmt = null;
  ResultSet set = null;
  // 构造方法初始化数据库连接,并将AutoCommit设定为False
  public SQLTransaction(Connection con) throws SQLException {
    this.conn = con;
    conn.setAutoCommit(false);
    this.stmt = con.createStatement();
  }

  public void executeUpdate(String sql) throws SQLException {
    //如果更新操作失败,回滚到事务起点并抛出异常
    try {
      stmt.executeUpdate(sql);
    }
    catch (SQLException e) {
      rollbackTransaction();
      throw e;
    }
  }

  public ResultSet executeQuery(String sql) throws SQLException {
    // 获得结果集。
    try {
      set = stmt.executeQuery(sql);
    }
    catch (SQLException e) {
      throw e;
    }
    finally {
      return set;
    }
  }

  public void commitTransaction() throws SQLException {
    // 事务结束,提交更新
    try {
      conn.commit();
      // 如果发生异常,回滚到事务起点
    }
    catch (Exception e) {
      rollbackTransaction();
      throw new SQLException("无法提交当前事务");
    }
  }

  public void rollbackTransaction() throws SQLException {
    // 回滚到事务起点
    try {
      conn.rollback();
      conn.setAutoCommit(true);
      // 如果在回滚过程中发生异常,忽略该异常
    }
    catch (SQLException e) {
      throw new SQLException(e.getMessage());
    }
  }

  public void close() throws SQLException {
    // 关闭连接
    try {
      if (set != null) {
        set.close();
      }
      if (stmt != null) {
        stmt.close();
      }
      if (conn != null) {
        conn.close();
      }
    }
    catch (SQLException e) {
      throw new SQLException(e.getMessage());
    }
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -