JdbcBatch

来源:互联网 发布:80后的网络歌曲有哪些 编辑:程序博客网 时间:2024/06/08 00:34
package me.gacl.demo;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import me.gacl.utils.JdbcUtils;
import org.junit.Test;


/**
* @ClassName: JdbcBatchHandleByStatement
* @Description: 使用prepareStatement实现JDBC批处理操作
* @author: 孤傲苍狼
* @date: 2014-9-20 下午10:05:45
*
*/ 
public class JdbcBatchHandleByPrepareStatement {


    @Test
    public void testJdbcBatchHandleByPrepareStatement(){
        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<1000008;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 + "秒!!");
    }
}