@Test
public void test4() {
Connection conn = null;
PreparedStatement ps = null;
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
// 设置不允许自动提交数据
conn.setAutoCommit(false);
String sql = "insert into goods(name) values (?)";
ps = conn.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
ps.setObject(1, "name_" + i);
//1."攒sql
ps.addBatch();
if (i % 500 == 0) {
// 2.执行batch
ps.executeBatch();
// 清空batch
ps.clearBatch();
}
}
// 统一提交数据
conn.commit();
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, ps);
}
}
在数据库中插入大量数据
最新推荐文章于 2025-03-21 10:26:31 发布