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(); } }