当前位置:   article > 正文

sql批量处理_xutils sql批处理

xutils sql批处理
  1. package Chapter19Jdbc.jdbc;
  2. import Chapter19Jdbc.utils.JDBCUtils;
  3. import org.junit.jupiter.api.Test;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.SQLException;
  7. /**
  8. * Written by 3778
  9. * 批处理
  10. */
  11. public class Batch {
  12. public static void main(String[] args) {
  13. }
  14. @Test
  15. public void method1(){
  16. Connection connection=null;
  17. PreparedStatement preparedStatement=null;
  18. try {
  19. connection = JDBCUtils.getConnection();
  20. String sql="insert into admin2 value(?,?)";
  21. preparedStatement = connection.prepareStatement(sql);
  22. long start =System.currentTimeMillis();
  23. for(int i=0;i<5000;i++){
  24. preparedStatement.setString(1,"张三"+i);
  25. preparedStatement.setInt(2,666);
  26. preparedStatement.executeUpdate();
  27. }
  28. long end=System.currentTimeMillis();
  29. System.out.println("普通方法耗时:"+(end-start));
  30. } catch (SQLException e) {
  31. e.printStackTrace();
  32. } finally {
  33. JDBCUtils.close(null,preparedStatement,connection);
  34. }
  35. }
  36. @Test
  37. public void method2(){
  38. Connection connection=null;
  39. PreparedStatement preparedStatement=null;
  40. try {
  41. connection = JDBCUtils.getConnection();
  42. String sql="insert into admin2 values (?,?)";
  43. preparedStatement = connection.prepareStatement(sql);
  44. long start =System.currentTimeMillis();
  45. for(int i=0;i<5000;i++){
  46. preparedStatement.setString(1,"张三"+i);
  47. preparedStatement.setInt(2,666);
  48. //将sql语句加入到批处理包中
  49. preparedStatement.addBatch();
  50. //当you1000条记录时再批量执行
  51. if((i+1)%1000 ==0){
  52. preparedStatement.executeBatch();
  53. //清空
  54. preparedStatement.clearBatch();
  55. }
  56. }
  57. long end=System.currentTimeMillis();
  58. System.out.println("批处理耗时:"+(end-start)); //3541
  59. } catch (SQLException e) {
  60. e.printStackTrace();
  61. } finally {
  62. JDBCUtils.close(null,preparedStatement,connection);
  63. }
  64. }
  65. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/964875?site
推荐阅读
相关标签
  

闽ICP备14008679号