1. 程式人生 > >mysql資料庫批處理

mysql資料庫批處理

package cn.itcast.demo5;

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

import org.junit.Test;

import cn.itcast.demo3.JdbcUtils;

/**
 * 批處理
 * @author cxf
 *
 */
public class Demo5 {
	/**
	 * pstmt物件內部有集合
	 * 1. 用迴圈瘋狂向pstmt中新增sql引數,它自己有模板,使用一組引數與模板罰沒可以匹配出一條sql語句
	 * 2. 呼叫它的執行批方法,完成向資料庫傳送!
	 * @throws SQLException 
	 */
	@Test
	public void fun5() throws SQLException {
		/*
		 * pstmt:
		 * > 新增引數到批中
		 * > 執行批!
		 */
		Connection con = JdbcUtils.getConnection();
		String sql = "INSERT INTO t_stu VALUES(?,?,?,?)";
		PreparedStatement pstmt = con.prepareStatement(sql);
		
		// 瘋狂的新增引數
		for(int i = 0; i < 10000; i++) {
			pstmt.setInt(1, i+1);
			pstmt.setString(2, "stu_" + i);
			pstmt.setInt(3, i);
			pstmt.setString(4, i%2==0?"男":"女");
			
			pstmt.addBatch();//新增批!這一組引數就儲存到集合中了。
		}
		long start = System.currentTimeMillis();
		pstmt.executeBatch();//執行批!
		long end = System.currentTimeMillis();
		
		System.out.println(end - start);//412764, 301
	}
}