日期:2014-05-16 浏览次数:20569 次
@Test public void testJDBCBatch() throws Exception{ final ApplicationContext ac= new ClassPathXmlApplicationContext("pdsu/zhang/jdbcAopDemo/applictionContext.xml"); // CallBack CountTime.getTime(new Handle(){ public void handler() throws Exception { Connection con=ac.getBean("datasource", DataSource.class).getConnection(); con.setAutoCommit(false); // 不设置 false 1000运行耗时:703ms :672ms PreparedStatement stmt = con.prepareStatement("INSERT INTO student VALUES (?, ?)"); for(int i=1;i<100000;i++){ // 循环本身 运行耗时:94ms stmt.setString(1, "zhangNo."+i); stmt.setString(2, "123"); //stmt.executeUpdate();//100运行耗时:109ms 1000运行耗时:657ms : 672ms stmt.addBatch(); //100运行耗时:32ms 1000运行耗时:250ms : 219ms } stmt.executeBatch(); con.commit(); // 10000运行耗时:1203ms 100000运行耗时:9406ms con.close(); } }); } class CountTime { public static void getTime(Handle handle) throws Exception { long start =System.currentTimeMillis(); handle.handler(); long end =System.currentTimeMillis(); System.out.println("运行耗时:"+(end-start)+"ms"); } } interface Handle{ public void handler() throws Exception; }
@Test public void testJDBCBatch2() throws Exception{ final ApplicationContext ac= new ClassPathXmlApplicationContext("pdsu/zhang/jdbcAopDemo/applictionContext.xml"); CountTime.getTime(new Handle(){ public void handler() throws Exception { Connection con=ac.getBean("datasource", DataSource.class).getConnection(); con.setAutoCommit(false); PreparedStatement stmt = con.prepareStatement("INSERT INTO student VALUES (?, ?)"); for(int i=1;i<10000;i++){ stmt.setString(1, "zhangNo."+i); stmt.setString(2, "123"); stmt.addBatch(); } stmt.executeBatch(); stmt.clearBatch(); for(int i=1;i<10000;i++){ stmt = con.prepareStatement("update student set pwd=?"); stmt.setString(1, i+""); stmt.addBatch(); // 运行耗时:2422ms } stmt.executeBatch();// 或者 executeUpdate()都行 stmt = con.prepareStatement("update student set pwd=? where name='zhang' "); stmt.setString(1, "123"); stmt.executeUpdate(); con.commit(); con.close(); /**操作 批量同统一提交 单个统一提交 单个直接提交 *1000条 运行耗时:391ms/437ms 运行耗时:8375ms 运行耗时:14969ms * 10K 运行耗时:3171ms */ } }); }