JDBC 批处理

package cn.itcast.batch;

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

import org.junit.Test;

import cn.itcast.jdbc.JDBCUtils;

public class BatchTest {
	@Test
	public void demo2() {
		long start = System.currentTimeMillis();
		// 向mysql 通过PreparedStatement 插入50000条数据
		Connection conn = null;
		PreparedStatement stmt = null;

		String sql = "insert into person values(?,?,?)";
		try {
			conn = JDBCUtils.getConnection();
			stmt = conn.prepareStatement(sql);// 预编译
			for (int i = 1; i <= 100000; i++) {
				stmt.setInt(1, i);
				stmt.setString(2, "name" + i);
				stmt.setString(3, "email" + i);
				// 将刚刚设置参数 加入批处理
				stmt.addBatch();

				if (i % 1000 == 0) { // 每1000条向数据库传递一次
					stmt.executeBatch();
					stmt.clearBatch();
				}
			}

			// 为了确保 缓存没有sql
			stmt.executeBatch();

			long end = System.currentTimeMillis();
			System.out.println("执行时间:" + (end - start));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(stmt, conn);
		}
	}

	@Test
	public void demo1() {
		// 使用Statement接口 批处理操作
		// 批处理操作一般没有查询语句, insert update delete其它sql
		Connection conn = null;
		Statement stmt = null;

		try {
			conn = JDBCUtils.getConnection();
			stmt = conn.createStatement();

			// 连续执行多条sql
			stmt.addBatch("create database mytest");
			stmt.addBatch("use mytest");
			stmt.addBatch("create table mytable(id int , name varchar(20))");
			stmt.addBatch("insert into mytable values(1,'aaa')");
			stmt.addBatch("insert into mytable values(2,'bbb')");
			stmt.addBatch("insert into mytable values(3,'ccc')");
			stmt.addBatch("insert into mytable values(4,'ddd')");

			stmt.addBatch("update mytable set name ='abcd' where id = 2");
			stmt.addBatch("delete from mytable where id =3 ");

			stmt.executeBatch();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(stmt, conn);
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值