@Test public void batch() throws SQLException { List<Student> students = new ArrayList<>() { { add(new Student(2231L, "Mon", 1,1, 110)); add(new Student(2232L, "Tus", 2,0, 1001)); add(new Student(2233L, "Wen", 3,1, 1110)); } }; try { conn.setAutoCommit(false); // todo start try (PreparedStatement ps = conn.prepareStatement("insert into students(id, grade, name, gender, score) values (?,?,?,?,?)")) { for (Student s : students) { ps.setObject(1, s.getId()); ps.setObject(2, s.getGrade()); ps.setObject(3, s.getName()); ps.setObject(4, s.getGender()); ps.setObject(5, s.getScore()); ps.addBatch(); } int[] ns = ps.executeBatch(); for (int n : ns) { logger.info(String.valueOf(n)); } } // todo end conn.commit(); } catch (SQLException e) { conn.rollback(); logger.info("err: ", e); } finally { conn.setAutoCommit(true); } } class Student { private Long id; private String name; private Integer grade; private Integer gender; private Integer score; ...... }
Sign in to make a reply
好先生的菜