package com.service.impl;

import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Service("UserServiceImpl")
public class UserServiceImpl implements UserService {
    @Autowired
    DataSource dataSource;
    @Override
    /**
     * 使用批处理add
     */
    public void addUserBatch() {
        try {
            Connection connection = dataSource.getConnection();
            String sql = "insert into wb_tbl_a (`company_id`) values(?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            System.out.println("开始执行");
            long start = System.currentTimeMillis();
            for (int i = 0; i < 100000; i++){
                preparedStatement.setInt(1, i);
                //将sql 语句加入到批处理包中 -> 看源码
                preparedStatement.addBatch();
                //当有1000条记录时，在批量执行
                if ((i + 1) % 1000 == 0){
                    preparedStatement.executeBatch();
                    //清空一把
                    preparedStatement.clearBatch();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("批处理的sql耗时：" + (end - start));
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
