批处理(Java)

 

package book.database;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 执行一批SQL执行
 * @author wuhailin
 *
 */
public class Batch {

 /**
  * 判断数据库是否支持批处理
  * @param con
  * @return
  */
 public static boolean supportBatch(Connection con){
  try{
   //得到数据库的元数据
   DatabaseMetaData md=con.getMetaData();
   return md.supportsBatchUpdates();
  }catch(SQLException e){
   e.printStackTrace();
  }
  return false;
 }
 /**
  * 执行一批SQL语句
  * @param con 数据库的连接
  * @param sqls 待执行的SQL数组
  * @return
  */
 public static int[] goBatch(Connection con,String[] sqls){
  if(sqls==null){
   return null;
  }
  Statement sm=null;
  try{
   sm=con.createStatement();
   for(int i=0;i<sqls.length;i++){
    //将所有的SQL语句添加到Statement
    sm.addBatch(sqls[i]);
   }
   //一次执行多条SQL语句
   return sm.executeBatch();
  }catch(SQLException e){
   e.printStackTrace();
  }finally{
   OperateDB.closeStatement(sm);
  }
  return null;
 }
 public static void main(String[] args)throws ClassNotFoundException,SQLException{
  String dbName="SGCC";
  String tableName="student_basic";
  String userName="sgccadmin";
  String password="sgccadmin";
  String[] sqls=new String[3];
  sqls[0]="update student_basic set score=95 where ";
  sqls[1]="insert into student_basic(ID,name,age,score,description) values(1,'lisi',17,78,'The name is bi')";
  sqls[2]="delete from student_basic where ";
  
  Connection con=null;
  try{
   //获得数据库的连接
   con=DBConnector.getOracleConnection(null,null,null, dbName, userName, password);
   boolean supportBatch=Batch.supportBatch(con);
   System.out.println("支持Batch?"+supportBatch);
   if(supportBatch){
    //执行一批SQL语句
    int[] results=Batch.goBatch(con, sqls);
    //分析执行的结果
    for(int i=0;i<sqls.length;i++){
     if(results[i]>=0){
      System.out.println("语句:"+sqls[i]+" 执行成功,影响了"+results[i]+"行数据");     
     }else if(results[i]==Statement.SUCCESS_NO_INFO){
      System.out.println("语句:"+sqls[i]+"执行成功,影响的行数未知");
     }else if(results[i]==Statement.EXECUTE_FAILED){
      System.out.println("语句:"+sqls[i]+"执行失败");
     }
    }
   }
  }catch(ClassNotFoundException e1){
   throw e1;
  }catch(SQLException e2){
   throw e2;
  }
  finally{
   OperateDB.closeConnection(con);
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值