package com.fd.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCBatch { public static void main(String[] args) { Connection conn = null; Statement statement = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iot", "root", "root"); //關鍵 設置為手動提交 conn.setAutoCommit(false); statement = conn.createStatement(); long start = System.currentTimeMillis(); for(int i = 0; i < 20000; i++) { statement.addBatch("insert into user(id, username, password, nickname) values('" + i + "', 'aaaaa', 'bbbbb', 'dccc')"); } statement.executeBatch(); conn.commit(); long end = System.currentTimeMillis(); System.out.println("end - start = " + (end - start) + " ms"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if(rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(statement != null) statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }