只建立一次连接,只提交一次
1、设置不允许自动提交数据
2、每500条,执行一次
3、所有数据执行完后,提交
@Test
public void test(){
long beginTime = System.currentTimeMillis();
String sql = "insert into fund_user (username, password, nick_name, salt, token) values(?,6,6,6,6)";
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
connection = JDBCUtils.getConnection();
//设置不允许自动提交数据
connection.setAutoCommit(false);
ps = connection.prepareStatement(sql);
for (int i = 0; i < 20000; i++){
ps.setObject(1, i);
//1."攒"sql
ps.addBatch();
if(i % 500 == 0){
//2.执行batch
ps.executeBatch();
//3.清空batch
ps.clearBatch();
}
}
connection.commit();
}catch (Exception e){
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}finally {
JDBCUtils.closeResource(connection, ps, rs);
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - beginTime);
}