package day01;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.Statement;public class Batch { /* * 批处理的三种方式 * * 预编译是用于执行DML语句(对数据批量的增删改) */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // exeBatchSql();// exeBatchPrepareSql(); exeBatchmixedSql(); } /* * 没有预编译的批处理(静态SQL) */ public static void exeBatchStaticSql() throws Exception { Connection connection = BaseSource.getConnection(); Statement statement = connection.createStatement(); for (int i = 0; i << font=""> 100; i++) { //批量的添加数据,缓存起来 statement.addBatch("insert into emp values('a'," + i + ",'b','c')"); if (i % 50 == 0) { // 如果批处理的数据太多,可以控制批处理的数量,但要记得clearBatch() statement.executeBatch(); statement.clearBatch(); } } statement.executeBatch();//缓存的SQL一次发给数据库 connection.close(); } /* * 预编译的批处理 */ public static void exeBatchPrepareSql() throws Exception { Connection connection = BaseSource.getConnection(); PreparedStatement prepareStatement = connection .prepareStatement("insert into emp values(?,?,?,?)"); for (int i = 100; i << font=""> 200; i++) { prepareStatement.setString(1, "a"); prepareStatement.setInt(2, i); prepareStatement.setString(3, "b"); prepareStatement.setString(4, "c"); prepareStatement.addBatch();// 设置完一条完整的数据后addBatch() } for (int i = 200; i << font=""> 300; i++) { prepareStatement.setString(1, "a"); prepareStatement.setInt(2, i); prepareStatement.setString(3, "b"); prepareStatement.setString(4, "c"); prepareStatement.addBatch(); } prepareStatement.executeBatch(); connection.close(); } /* * 预编译和静态SQL 混合使用 */ public static void exeBatchmixedSql() throws Exception { Connection connection = BaseSource.getConnection(); PreparedStatement prepareStatement = connection .prepareStatement("insert into emp values(?,?,?,?)"); prepareStatement.setString(1, "a"); prepareStatement.setInt(2, 400); prepareStatement.setString(3, "b"); prepareStatement.setString(4, "c"); prepareStatement.addBatch();//预编译的批处理 prepareStatement.addBatch("insert into emp values('a'," + 401 + ",'b','c')");//静态的预编译 prepareStatement.executeBatch(); connection.close(); }}