使用JDBC批量插入10万条数据
1.环境准备
创建项目并添加相关依赖
2.编写代码
package com.kwg.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author wengQ
* @Title:
* @Description:
* @date 2020-7-5 22:18
*/
public class TestJdbcConnection {
public static void main(String[] args) {
//Connection连接对象
Connection con = null;
//jdbc驱动
String driver = "com.mysql.jdbc.Driver";
//数据库URL地址
String url = "jdbc:mysql://localhost:3306/demo?&useSSL=false&serverTimezone=UTC";
//连接数据库的用户名及密码
String userName = "root";
String password = "root";
//SQL执行对象
PreparedStatement preparedStatement;
try {
//开始时间
Long startTime = System.currentTimeMillis();
//注册JDBC驱动程序
Class.forName(driver);
//建立连接
con = DriverManager.getConnection(url, userName, password);
//准备SQL
String sql = "insert into tb_user values(?,?)";
/**
* 取消自动提交
*
* 没有setAutoCommit(false);那么对于每一条insert语句,都会产生一条log
* 写入磁盘,所以虽然设置了批量插入,但其效果就像单条插入一样,导致插入速度十分缓慢
*/
con.setAutoCommit(false);
//预编译SQL
preparedStatement = con.prepareStatement(sql);
//循环插入100000万条数据
for (int i = 1; i <= 100000; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "测试批量插入数据" + i);
preparedStatement.addBatch();
// 1w条记录插入一次
if (i % 10000 == 0) {
preparedStatement.executeBatch();
con.commit();
}
}
// 最后插入不足1w条的数据
preparedStatement.executeBatch();
con.commit();
Long endTime = System.currentTimeMillis();
System.out.println("插入10万条数据共耗时 : " + ((endTime - startTime) / 1000) + "秒");
} catch (ClassNotFoundException e) {
System.out.println("数据库驱动没有安装");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
3.查看执行结果
插入时间跟网络情况有关,平均在6~10秒之间