在JDBC一次插入多个表、多条记录

来源:互联网 发布:ionic lab for mac 编辑:程序博客网 时间:2024/05/16 07:37

原文链接

在jdbc操作中,通过事务操作,一次可以插入多个表 ,多条记录:

public static void insertBatch() {
  int count[];
  int count1[];
  Boolean isinsert = false;
  Connection con = null;
  PreparedStatement pst = null;
  PreparedStatement pst1 = null;
  try {
   con = getCon();
   con.setAutoCommit(false);                                   // 需要用到事务,不能让他自动提交,需要手动提交
   pst = con.prepareStatement(INSERT_SQL);          // INSERT_SQL表示对一张表的插入记录
   pst1 = con.prepareStatement(INSERT_SQL1);      // INSERT_SQL表示对另一张表的插入记录

   pst.setString(1, "name1");
   pst.setInt(2, 26);
   pst.setString(3, "job1");
   pst.addBatch();
   
   pst.setString(1, "name2");
   pst.setInt(2, 12);
   pst.setString(3, "job2");
   pst.addBatch();
   -------可以对pst进行更多的插入-----------
   pst1.setString(1, "name--1");
   pst1.setInt(2, 26);
   pst1.setString(3, "job--1");
   pst1.addBatch();
   
   pst1.setString(1, "name--2");
   pst1.setInt(2, 26);
   pst1.setString(3, "job--2");
   pst1.addBatch();
   -------可以对pst1进行更多的插入-----------
   count = pst.executeBatch();
   count1 = pst1.executeBatch();
   con.commit();                 //提交事务,这个非常重要
   
   for(int i : count){
    if(i == 0) {
     con.rollback();              // 回滚,非常重要
     System.out.println("======出现异常,回滚=========");
    }

   }

   
   for(int i : count1){
    if(i == 0) {
     con.rollback();          // 回滚,非常重要
     System.out.println("==111====出现异常,回滚====111=====");
    }

   }

     
  }
 catch (SQLException e) {
   try {
    con.rollback();            // 回滚,非常重要
   }
 catch (SQLException e1) {
    e1.printStackTrace();
   }

   System.out.println("------出现异常,回滚----------");
   e.printStackTrace();
  }
 finally {
   cloCon(con,pst);
  }

 }