java中批量执行sql语句

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


public class tttt {

 public static boolean supportBatch(Connection con)
 {
  try
        {
   DatabaseMetaData md=con.getMetaData();
   return md.supportsBatchUpdates();
        }
  catch(SQLException e)
  {
   e.printStackTrace();
  }
        return false;
 }
 
 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++)
   {
    sm.addBatch(sqls[i]);
   }
   
   return sm.executeBatch();
  }
  catch(SQLException e)
  {
      e.printStackTrace(); 
  }
  return null;
 }
 
 /**
  * @param args
  * @throws IllegalAccessException
  * @throws InstantiationException
  */
 public static void main(String[] args) throws ClassNotFoundException,SQLException, InstantiationException, IllegalAccessException{
  // TODO Auto-generated method stub

  String userName="root";
  String password="709394";
  
  String[] sqls=new String[2];
  sqls[0]="insert into yjyj(username) values('jiejie2ddd')"; 
  sqls[1]="delete from yjyj where username='yunjie'";
  //在这里可以自己添加多个需要执行的语句
  Connection con=null;
  try
  {
   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
   con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yyjj",userName,password);
   boolean supportBatch=tttt.supportBatch(con);
   System.out.println(supportBatch);
   
   if(supportBatch)
   {
    int[] results=tttt.goBatch(con, sqls);
    
   }
  }
  catch(SQLException e)
  {
   e.printStackTrace();
  }
 }

}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值