赞
踩
- package Chapter19Jdbc.jdbc;
-
- import Chapter19Jdbc.utils.JDBCUtils;
- import org.junit.jupiter.api.Test;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
-
- /**
- * Written by 3778
- * 批处理
- */
- public class Batch {
- public static void main(String[] args) {
-
- }
- @Test
- public void method1(){
- Connection connection=null;
- PreparedStatement preparedStatement=null;
- try {
- connection = JDBCUtils.getConnection();
- String sql="insert into admin2 value(?,?)";
- preparedStatement = connection.prepareStatement(sql);
- long start =System.currentTimeMillis();
- for(int i=0;i<5000;i++){
- preparedStatement.setString(1,"张三"+i);
- preparedStatement.setInt(2,666);
- preparedStatement.executeUpdate();
- }
- long end=System.currentTimeMillis();
- System.out.println("普通方法耗时:"+(end-start));
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- JDBCUtils.close(null,preparedStatement,connection);
- }
- }
-
- @Test
- public void method2(){
- Connection connection=null;
- PreparedStatement preparedStatement=null;
- try {
- connection = JDBCUtils.getConnection();
- String sql="insert into admin2 values (?,?)";
- preparedStatement = connection.prepareStatement(sql);
- long start =System.currentTimeMillis();
- for(int i=0;i<5000;i++){
- preparedStatement.setString(1,"张三"+i);
- preparedStatement.setInt(2,666);
- //将sql语句加入到批处理包中
- preparedStatement.addBatch();
- //当you1000条记录时再批量执行
- if((i+1)%1000 ==0){
- preparedStatement.executeBatch();
- //清空
- preparedStatement.clearBatch();
- }
- }
- long end=System.currentTimeMillis();
- System.out.println("批处理耗时:"+(end-start)); //3541
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- JDBCUtils.close(null,preparedStatement,connection);
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。