Skip to content

Latest commit

 

History

History
58 lines (49 loc) · 1.44 KB

批處理.md

File metadata and controls

58 lines (49 loc) · 1.44 KB

批處理

介紹

  • 批處理就是一批一批的處理,而不是一個一個處理。
  • 即一次向服務器發送多條 SQL 語句,然後由服務器一次性處理。
  • 批處理只針對更新(增、刪、改)語句,與查詢無關。

PreparedStatement 批處理

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

import org.junit.Test;

import demo3.JdbcUtils;

/**
 * 批處理
 * @author jack870131
 *
 */
public class Demo5 {
	/**
	 * 批處理內部有集合
	 * 1. 用循環向 pstmt 中添加 sql 參數,他自己有模板,使用一組參數與模板可以匹配出一條sql語句
	 * 2. 調用他的執行批方法,完成向數據庫發送
	 * @throws SQLException 
	 */
	@Test
	public void fun1() 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?"Male":"Female");
			
			pstmt.addBatch(); //添加批,這組參數就保存到集合中了
		}
		long start = System.currentTimeMillis();
		pstmt.executeBatch(); //執行批
		long end = System.currentTimeMillis();
		
		System.out.println(end - start);
	}
}