原因:数据库默认没完成一次操作就自动提交一次commit(), 所以在添加开始时先connection.setAutoCommit(false); 然后在添加结束后connection.commit();
例如:
@Test public void lotInsert() throws Exception { JDBCUtil util = new JDBCUtil(); Connection connection = null; java.sql.PreparedStatement ps = null; try { connection = util.Connection(); //取消每次操作都提交,必须有否则和单个添加一样 connection.setAutoCommit(false); String sql = "insert into goods(name) value(?);"; ps = connection.prepareStatement(sql); long begin = System.currentTimeMillis(); //批量添加 for (int i = 1; i <= 2000; i++) { ps.setObject(1 , "name_" + i); ps.addBatch(); if(i % 500 == 0){ ps.executeBatch(); connection.commit(); ps.clearBatch(); } } //最后再提交 connection.commit(); long end = System.currentTimeMillis(); System.out.println(end - begin); } catch (Exception e) { e.printStackTrace(); }finally { util.Close(connection , ps); } }