赞
踩
/**
* 1. 直接for循环多次插入
*
* 2. 在(1)的基础上,开启sql的批量处理,利用Batch机制,先将多个sql语句存起来,然后一起执行这些sql语句
* 2.1 有三个方法addBatch()、executeBatch()、clearBatch()
* 2.2 mysql服务器默认是关闭批量处理的
* 解决方法:
* a. 通过一个参数,开启mysql对批量处理的支持【?rewriteBatchedStatements=true】
* 写在 url 后面
* b. 使用较新的mysql驱动:mysql-connector-java-5.1.37-bin.jar
*
* 3. 在(2)的基础上,设置不允许自动提交,等到所有的sql都执行完了,再提交数据
*/
// 在下面的代码中
Connection conn = Utils_01.getConnection(); // 这是获取Connection的连接对象
Utils_01.closeResource(conn, ps); // 这是关闭Connection的资源
@Test public void insert1() throws Exception { int cnt = 200000; long start = new Date().getTime(); // 1. 获取连接 Connection conn = Utils_01.getConnection(); // 2. 预编译 String sql = "insert into goods (name) values (?)"; PreparedStatement ps = conn.prepareStatement(sql); // 3. 插入数据 for (int i = 1; i <= cnt; i ++ ) { ps.setObject(1, "name_" + i); ps.execute(); } // 4. 关闭资源 Utils_01.closeResource(conn, ps); long end = new Date().getTime(); System.out.println(end - start); }
@Test public void insert2() throws Exception { int cnt = 2000000; long start = new Date().getTime(); // 1. 获取连接 Connection conn = Utils_01.getConnection(); // 2. 预编译 String sql = "insert into goods (name) values (?)"; PreparedStatement ps = conn.prepareStatement(sql); // 3. 插入数据 for (int i = 1; i <= cnt; i ++ ) { ps.setObject(1, "name_" + i); // 3.1 攒sql语句 ps.addBatch(); // 3.2 到达一定的量时,执行sql语句,并将赞的sql清空;而且,为了防止遗漏,到达最后一个时,也要执行 if (i % 500 == 0 || i == cnt) { ps.executeBatch(); ps.clearBatch(); } } // 4. 关闭资源 Utils_01.closeResource(conn, ps); long end = new Date().getTime(); System.out.println(end - start); }
@Test public void insert_3() throws Exception { int cnt = 2000000; long start = new Date().getTime(); // 1. 获取连接 Connection conn = Utils_01.getConnection(); conn.setAutoCommit(false); // 同时设置不可自动提交 // 2. 预编译 String sql = "insert into goods (name) values (?)"; PreparedStatement ps = conn.prepareStatement(sql); // 3. 插入数据 for (int i = 1; i <= cnt; i ++ ) { ps.setObject(1, "name_" + i); // 3.1 攒sql语句 ps.addBatch(); // 3.2 到达一定的量时,执行sql语句,并将赞的sql清空;而且,为了防止遗漏,到达最后一个时,也要执行 if (i % 500 == 0 || i == cnt) { ps.executeBatch(); ps.clearBatch(); } } // 4. 关闭资源 conn.commit(); // 关闭资源的之前,手动提交数据 Utils_01.closeResource(conn, ps); long end = new Date().getTime(); System.out.println(end - start); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。