MySQL的批处理


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倍以上!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM