public class BatchTest { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { int empNo = 0; if (args != null && args.length == 1) { empNo = Integer.parseInt(args[0]); } // 第一步,加载数据库驱动 // 驱动会根据数据库的不同而不同 Class.forName("oracle.jdbc.driver.OracleDriver"); // 第二步,取得数据库连接 // 不同的数据库连接串不同 String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:bjpowernode"; String username = "scott"; String password = "tiger"; conn = DriverManager.getConnection(dbUrl, username, password); String sql = "insert into emp(empno, ename) values(?, ?)"; System.out.println("sql=" + sql); // 第三步,创建PreparedStatement,执行sql语句 pstmt = conn.prepareStatement(sql); for (int i = 4000; i < 4020; i++) { pstmt.setInt(1, i); pstmt.setString(2, "emp_" + i); // 注意batch的使用 pstmt.addBatch(); } // 批量执行 pstmt.executeBatch(); System.out.println("添加员工成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { // 遵循从里到外关闭的原则 if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { } } // 必须关闭Connection if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } } }