1、批处理:
当要执行某条SQL语句很多次时。例如,批量添加数据;使用批处理的效率要高的多。
2、如何实现批处理
实践:
package com.dgd.test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.*; public class Test { public static void main(String[] args) throws SQLException, ClassNotFoundException, FileNotFoundException { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //url,批处理需要添加一个参数:? 符号后面,多个参数之间用 & 符号; 添加参数为 rewriteBatchedStatements=true String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&rewriteBatchedStatements=true"; //获取连接 Connection conn = DriverManager.getConnection(url, "root", "123456"); System.out.println(conn.getClass()); //编写sql语句 String sql="INSERT INTO stu VALUES(null ,?)"; //创建 PreparedStatement 对象 PreparedStatement s = conn.prepareStatement(sql); //设置 ? 值 for (int i = 0; i <=1000 ; i++) { s.setObject(1,"测试数据"+i); //添加到批处理中,先攒着,本质上(底层)有一个缓冲区。先缓冲所有的要执行的SQL语句 s.addBatch(); } //循环外面,执行这组批处理 s.executeBatch(); //如果需要返回值,需要用 int[] 数组接受 // int[] executeBatch=s.executeBatch(); //关闭资源 s.close(); conn.close(); } }