原文链接:https://www.cnblogs.com/fnz0/p/5713102.html
有这么几种方式:
1、存储过程
2、普通for循环插入
3、事务提交
4、批量提交
5、批量操作+事务
经过测试,效率最高的方式为“批量提交”和“批量操作+事务”
在此记录下“批量操作+事务”的代码,如下:
package peace;
import java.sql.*;
public class Demo {
public static void main(String[] args) {
String url = "jdbc:mysql://127.0.0.1:3306/peace?rewriteBatchedStatements=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
String user = "root";
String pwd = "root";
Connection con = null;
PreparedStatement pstm = null;
ResultSet rt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,user,pwd);
String sql = "insert into test1(a,b,c,d) values (?,CONCAT('abc',?),?,?)";
pstm = con.prepareStatement(sql);
con.setAutoCommit(false);
Long startTime = System.currentTimeMillis();
for(int i=1; i<10000000; i++) {
pstm.setString(1,"test");
pstm.setInt(2, i);
pstm.setString(3, "测试");
pstm.setInt(4, i+2);
pstm.addBatch();
}
pstm.executeBatch();
con.commit();
Long endTime = System.currentTimeMillis();
System.out.println("已执行完成,耗时: "+ (endTime - startTime));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(pstm!=null){
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
实际测试结果:
插入1000W条数据耗时 272887ms
批量插入数据报错问题处理
数据插入过程中会出现如下问题,当批量提交1000W数据(视sql数据量大小而定)时会出现com.mysql.cj.jdbc.exceptions.PacketTooBigException: Packet for query is too large的错误,此时我们需要加大mysql的max_allowed_packet,如下:
修改my.ini文件,在[mysqld]部分找到max_allowed_packet将值改大