package day2;
import java.sql.*;
/**
 * 测试JDBC事务功能
 * @author teacher
 *
 */
public class TransactionDemo {

  /**
   * @param args
   */
  public static void main(String[] args) {
      System.out.println(changeSalary(1001, 8999)?"ok":"error");
  }
  /**
   * 修改某员工的薪水为新值,并记录日志
   * @param empno 要修改薪水的员工编码
   * @param newSalary 新的薪水值
   * @return 修改成功并日志记录成功,则返回true,否则返回false
   */
  public static boolean changeSalary(int empno, double newSalary){
    boolean flag = false;
    String sql1 = "update emp_ning set salary = ? " + " where empno = ?";
    String sql2 = "insert into logs_ning(id, who, what)" + " values(seq_logs_ning.nextval, user, 'update salary')";
    
    Connection conn = ConnectionUtils.getConnection();
    PreparedStatement stmt = null;
    try {
      conn.setAutoCommit(false);//关闭自动提交
      stmt = conn.prepareStatement(sql1); //sql1:update
      stmt.setDouble(1, newSalary);
      stmt.setInt(2, empno);
      int n1 = stmt.executeUpdate();
      stmt = conn.prepareStatement(sql2); //sql2:insert
      int n2 = stmt.executeUpdate();
      
      if (n1 == 1 && n2 == 1){    //这里的数值是影响记录的数目
        conn.commit();//////两条都成功,提交
        flag = true;
      }else{
        conn.rollback();//////任意一条不成功,但没有异常,回滚
      } 
    } catch (SQLException e) {
      try {
        conn.rollback();//////出现异常,回滚
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
    } finally{
      ConnectionUtils.close(stmt);
      ConnectionUtils.close(conn);
    }  
    return flag;
  }
  
}

 

相关文章:

  • 2021-08-29
  • 2022-12-23
  • 2022-02-16
  • 2021-09-10
猜你喜欢
  • 2021-12-14
  • 2022-12-23
  • 2021-08-08
  • 2021-09-03
  • 2021-10-08
相关资源
相似解决方案