1.直接循环插入100万条数据
pstmt = getConn().prepareStatement("insert into bigdata values (?,?,?)");
long bTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
pstmt.setString(1,"id"+i);
pstmt.setString(2,"name"+i);
pstmt.setString(3,"passwd");
pstmt.execute();
}
执行耗时 640135毫秒
2.使用批处理
for (int i = 0; i < 1000000; i++) {
pstmt.setString(1,"id"+i);
pstmt.setString(2,"name"+i);
pstmt.setString(3,"passwd");
pstmt.addBatch();
if (i % 10000 == 0) {
pstmt.executeBatch();
conn.commit();
//关闭分段计时
long eTime = System.currentTimeMillis();
//输出
System.out.println("成功插入1W条数据耗时:" + (eTime - bTime) + "毫秒");
bTime = System.currentTimeMillis();
}
// pstmt.execute();
}
pstmt.executeBatch();
conn.commit();
提交耗时 2081毫秒
多线程处理再100万数据下和单线程影响不大
3.启动十个线程插入一千万条数据 19650毫秒
for (int i = 0; i < 10; i++) {
//ThreadPoolExecutor的execute方法
executor.execute(new Test());
}
countDownLatch.await();
//多线程任务执行完毕,关闭线程池
executor.shutdown();
long eTime1 = System.currentTimeMillis();
System.out.println("共耗时:" + (eTime1 - bTime1) + "毫秒");
}
public void run() {
try {
new JDBCUtils().insert();
} catch (Exception e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
4.启动一个线程插入 一千万条数据耗时为 23334毫秒
5.mysql百万数据批处理使用时间148722毫秒
6.mysql百万数据使用十个线程时间为81397毫秒