MySQL开启批处理

MySQL默认关闭批处理

开启方法

在原始的URL尾部添加开启指令,如下标注语句
url = jdbc:mysql://localhost:3306/mydb3 ?rewriteBatchedStatements=true

添加批处理

调用preparedStatement中的addBatch()方法,将一句sql添加到批中,循环调用,则可添加大量sql语句到批中。

执行批处理

调用executeBatch()方法,此方法为继承父类Statament中的方法。

批处理可将sql的执行效率大大提升

范例代码

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import cn.itcast.jdbcUtils.JdbcUtils;

public class Demo5 {
	/**
	 * 批处理
	 * pstmt对象内部有集合
	 * 1.用循环向pstmt中添加sql参数,它有自己的模板,使用一组参数与模板可以匹配出一条sql语句
	 * 2.最后调用执行批方法,完成向数据库发送
	 * @throws Exception 
	 */
	public void fun5() throws Exception {
		/*
		 * pstmt:
		 * >添加参数到批中
		 * >执行批
		 */
		
		Connection con = JdbcUtils.getConnection();
		String sql = "insert into t_stu values(?,?,?,?)";
		PreparedStatement pstmt = (PreparedStatement) 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);
	}
	
	
	public static void main(String[] args) throws Exception {
		Demo5 demo5 = new Demo5();
		demo5.fun5();
	}
}
原文地址:https://www.cnblogs.com/dwwzone/p/12859260.html