yxhxj2006

常用链接

统计

最新评论

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

 

在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(
226);
   pst.setString(
3"job1");
   pst.addBatch();
   
   pst.setString(
1"name2");
   pst.setInt(
212);
   pst.setString(
3"job2");
   pst.addBatch();
   
-------可以对pst进行更多的插入-----------
   pst1.setString(
1"name--1");
   pst1.setInt(
226);
   pst1.setString(
3"job--1");
   pst1.addBatch();
   
   pst1.setString(
1"name--2");
   pst1.setInt(
226);
   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);
  }

 }

 

posted on 2012-07-17 14:40 奋斗成就男人 阅读(2626) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: