MySQL默认是关闭批处理的,所以我们在默认状态下(批处理未打开)向数据库中存入10000条数据,核心代码如下:

package cn.itcast.demo5;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
import cn.itcast.demo3.JdbcUtils;
public class Demo5 {
    @Test
    public void fun5() throws SQLException {
        /*
         * pstmt:
         * > 添加参数到批中
         * > 执行批!
         */
        Connection con = JdbcUtils.getConnection();
        String sql = "INSERT INTO t_stu VALUES(?,?,?,?)";
        PreparedStatement pstmt = con.prepareStatement(sql);
        
        // 疯狂的添加参数
        for(int i = 0; i < 10000; i++) {
            pstmt.setInt(1, i+1);
            pstmt.setString(2, "stu_" + i);
            pstmt.setInt(3, i);
            pstmt.setString(4, i%2==0?"男":"女");            
            pstmt.addBatch();//添加批!这一组参数就保存到集合中了。
        }
        long start = System.currentTimeMillis();
        pstmt.executeBatch();//执行批!
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}

上述程序执行结束耗费时间412764MS

这是打开MySQL的批处理,打开方式:

  将MySQL参数  url=jdbc:mysql://localhost:3306/exam

  改为        url=jdbc:mysql://localhost:3306/exam?rewriteBatchedStatements=true

再次执行程序,耗时301MS,速度快了1000倍以上!

相关文章:

  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-26
  • 2021-08-01
  • 2022-03-09
  • 2021-11-25
  • 2021-09-25
  • 2022-12-23
  • 2021-11-20
相关资源
相似解决方案