欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

batch插入机制

程序员文章站 2022-05-01 12:40:05
...
package com.DaoImp;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.junit.Test;

import com.util.Throw;

public class Batch {
	@Test
	public void test() throws Exception{
		Connection con=Throw.getConnetion();
		PreparedStatement pre=con.prepareStatement("insert into LianXi(id,dir_id) values(?,?);");
	    long start=System.currentTimeMillis();
	    for(int i=1;i<=50;i++){
	    	pre.setLong(1, i);
	    	pre.setLong(2, i+1);
	    	pre.executeUpdate();
	    }
	    long end =System.currentTimeMillis();
	    System.out.println("用时"+(end-start)+"ms");
	    Throw.myClose(pre, con, null);
	}
	@Test
	public void test1() throws Exception{
		Connection con=Throw.getConnetion();
		//PreparedStatement pre =con.prepareStatement("insert into LianXi(id,dir_id) values(?,?);");
		//这样是错误的,因为batch插入的机制是insert into LianXi(id,dir_id) values(?,?),(?,?),(?,?)++
		//有;后变成了insert into LianXi(id,dir_id) values(?,?);,(?,?);,(?,?);++
		PreparedStatement pre =con.prepareStatement("insert into LianXi(id,dir_id) values(?,?)");
		 long start=System.currentTimeMillis();
		    for(int i=1;i<=500;i++){
		    	pre.setInt(1, i);
		    	pre.setInt(2, i+1);
		    	pre.addBatch();
		    	if(i%50==0){
		    		pre.executeBatch();
		    		pre.clearBatch();
		    	}
		    }
		    long end =System.currentTimeMillis();
		    System.out.println("用时"+(end-start)+"ms");
		    Throw.myClose(pre, con, null);
	}

}

相关标签: batch