• Mysql 批处理多条sql语句


    package cn.itcast.demo;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import org.junit.Test;
    
    import cn.itcast.utils.JdbcUtils;
    
    public class Demo3 {
    
        /**
         * jdbc批处理的两种方式:statement 和 preparedstatement
         create table testbatch
         (
             id int primary key,
             name varchar2(20)
         );
          
         */
        
        @Test
        public void testbatch1(){
            
            Connection conn = null;
            Statement st = null;
            ResultSet rs = null;
            
            try{
                conn = JdbcUtils.getConnection();
                String sql1 = "insert into testbatch(id,name) values(1,'aaa')";
                String sql2 = "insert into testbatch(id,name) values(2,'bbb')";
                String sql3 = "delete from testbatch where id=1";
                
                st = conn.createStatement();
                st.addBatch(sql1);
                st.addBatch(sql2);
                st.addBatch(sql3);
                
                st.executeBatch(); 
                st.clearBatch();
            }catch (Exception e) {
                e.printStackTrace();
            }finally{
                JdbcUtils.release(conn, st, rs);
            }
        }
        
        @Test
        public void testbatch2(){
            
            long starttime = System.currentTimeMillis();
            Connection conn = null;
            PreparedStatement st = null;
            ResultSet rs = null;
            
            try{
                conn = JdbcUtils.getConnection();
                String sql = "insert into testbatch(id,name) values(?,?)";
                st = conn.prepareStatement(sql);
                
                for(int i=1;i<10000008;i++){  //i=1000  2000
                    st.setInt(1, i);
                    st.setString(2, "aa" + i);
                    st.addBatch();
                    
                    if(i%1000==0){
                        st.executeBatch();
                        st.clearBatch();
                    }
                }
                st.executeBatch();
                
            }catch (Exception e) {
                e.printStackTrace();
            }finally{
                JdbcUtils.release(conn, st, rs);
            }
            
            long endtime = System.currentTimeMillis();
            
            System.out.println("程序花费时间:" + (endtime-starttime)/1000 + "秒!!");
        }
    
    }
  • 相关阅读:
    白书上的BellmanFord模板
    c#中的分部类和分部方法
    c#类
    浪潮gs开发平台学习平台快速开发入门
    c#学习积累
    自定义属性编辑器
    hibernate 中的hql,nativesql ,list(),iterate() 的使用规则
    c#继承
    浪潮gs中间件服务器,客户端,数据库sqlserver安装注意事项
    c#接口
  • 原文地址:https://www.cnblogs.com/lichone2010/p/3178677.html
Copyright © 2020-2023  润新知