我们这里使用jdbc来插入
测试:用jdbc插入,20万条数据只需要8s,推荐
下面看代码:
package com.zoo.lion.modules.test.mysql; import org.junit.Test; import java.sql.*; /** * @Author: xf * @Date: 2019/7/15 10:00 * @Version 1.0 */ public class Insert { private String url = "jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF8&characterSetResults=UTF8&serverTimezone=Asia/Shanghai" + "&rewriteBatchedStatements=true"; private String username = "root"; private String password = "root"; @Test public void jdbc() { Connection connection = null; PreparedStatement preparedStatement = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(url, username, password); String sql = "INSERT INTO test(id,name,age) VALUES(null,?,60)"; preparedStatement = connection.prepareStatement(sql); long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { preparedStatement.setString(1, "周润发" + i); preparedStatement.addBatch(); } preparedStatement.executeBatch(); long end = System.currentTimeMillis(); System.out.println("用时:" + (end - start)); } catch (Exception e) { e.printStackTrace(); } finally { try { if (connection != null) { connection.close(); } if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
注意黑色加粗部分,rewriteBatchedStatements=true 开启批量插入,插入只执行一次,所有插入比较快。
修改mysql的max_allowed_packet,如果jdbc最大连接包太小,会报错,所以需要修改
修改步骤如下:
1. show VARIABLES like '%max_allowed_packet%'; 执行语句查询最大包长度。
2. set global max_allowed_packet = 300*1024*1024;执行语句设置最大包长度,改为300M。
再次查询,会发现长度变了
max_allowed_packet 314572800
如果修改不成功,在mysql文件下找到my.ini文件,在【mysqlId】下添加一个配置:
max_allowed_packet = 300M
最后重启mysql,再次查询,长度发生变化了,再次执行批量插入,就不会报错了。