UserServiceImpl.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.service.impl;
  2. import com.service.UserService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import javax.sql.DataSource;
  6. import java.sql.Connection;
  7. import java.sql.PreparedStatement;
  8. import java.sql.SQLException;
  9. @Service("UserServiceImpl")
  10. public class UserServiceImpl implements UserService {
  11. @Autowired
  12. DataSource dataSource;
  13. @Override
  14. /**
  15. * 使用批处理add
  16. */
  17. public void addUserBatch() {
  18. try {
  19. Connection connection = dataSource.getConnection();
  20. String sql = "insert into wb_tbl_a (`company_id`) values(?)";
  21. PreparedStatement preparedStatement = connection.prepareStatement(sql);
  22. System.out.println("开始执行");
  23. long start = System.currentTimeMillis();
  24. for (int i = 0; i < 100000; i++){
  25. preparedStatement.setInt(1, i);
  26. //将sql 语句加入到批处理包中 -> 看源码
  27. preparedStatement.addBatch();
  28. //当有1000条记录时,在批量执行
  29. if ((i + 1) % 1000 == 0){
  30. preparedStatement.executeBatch();
  31. //清空一把
  32. preparedStatement.clearBatch();
  33. }
  34. }
  35. long end = System.currentTimeMillis();
  36. System.out.println("批处理的sql耗时:" + (end - start));
  37. connection.close();
  38. } catch (SQLException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }