事务处理

/************事务处理*****************/
 public static void main(String[] args) {
  String sql1 = "insert into stuInfo values(123910,'小建',23,'男','普宁')";
  String sql2 = "insert into stuInfo values(123911,'大建',25,'男','普宁')";
  try {
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
  Connection conn = null;
  Statement stm = null;
  try {
   conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=StuDB","sa","sasa");
   stm = conn.createStatement();
   conn.setAutoCommit(false);//false代表事务不会自动提交,默认为true
   stm.executeUpdate(sql1);
   stm.executeUpdate(sql2);
   conn.commit();//事务提交
   System.out.println("事务提交成功!");
  } catch (SQLException e) {
   try {
    conn.rollback();//事务回滚
   } catch (SQLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
   System.out.println("添加有误,事务回滚!");
  }finally{
   try {
    stm.close();
    conn.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

posted @ 2014-07-04 23:59  单方面  阅读(193)  评论(0编辑  收藏  举报