声明:本人使用的是公司2核4GB服务器进行的测试,插入速度受服务器限制
第一种方式: 批处理禁用自动提交功能
String jdbcUrl = "jdbc:sqlserver://121.37.155.***:46943;databaseName=ruoyi;useUnicode=true&characterEncoding=utf-8";
String dbUser = "ic_gas_read_****";
String dbPassword = "ic_gas_read_*****";
@Test
public void bulkSubmissionTest1() throws SQLException {
long start = System.currentTimeMillis();
Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
String sql = "insert into cba (id, name) VALUES (?,null)";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for (int i = 1; i <= 100000; i++) {
ps.setString(1, String.valueOf(i));
ps.addBatch();
}
ps.executeBatch();
ps.clearBatch();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ps.close();
conn.close();
}
System.out.println("十万条数据插入用时:" + (System.currentTimeMillis() - start)+"【单位:毫秒】");
}
十万条数据用时 2.9秒
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/83577db41d6748438507c2d82a98f5bd.png)
第二种方式: 使用批处理
String jdbcUrl = "jdbc:sqlserver://121.37.155.***:46943;databaseName=ruoyi;useUnicode=true&characterEncoding=utf-8";
String dbUser = "ic_gas_read_****";
String dbPassword = "ic_gas_read_****";
@Test
public void bulkSubmissionTest1() throws SQLException {
long start = System.currentTimeMillis();
Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
String sql = "insert into cba (id, name) VALUES (?,null)";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
for (int i = 1; i <= 100000; i++) {
ps.setString(1, String.valueOf(i));
ps.addBatch();
if (i%500==0){
ps.executeBatch();
ps.clearBatch();
}
}
ps.executeBatch();
ps.clearBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ps.close();
conn.close();
}
System.out.println("百万条数据插入用时:" + (System.currentTimeMillis() - start)+"【单位:毫秒】");
}
十万条数据用时 69秒
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/639dd71b467a4155b38b586290a60461.png)
二者间的区别
- 这两段代码的主要区别在于它们处理事务的方式。第一种代码示例在执行批量插入操作之前禁用了自动提交功能,并在执行完所有操作后显式地提交了事务。这意味着在执行批量插入操作期间,所有更改都将在事务范围内进行。这种方法可以确保数据的一致性和完整性,尤其是在处理多个操作时。
- 第二种代码示例没有显式地处理事务。它将每500个插入操作分为一个批次,并在每个批次后执行 executeBatch()。这种方法可能会导致在执行过程中,部分插入操作已经提交,而其他操作尚未提交。这可能会导致数据的不一致性和不完整性,尤其是在处理大量操作时。