1、开启MySQL的批处理功能:在配置文件的url后面添加?rewriteBatchedStatements=true。
public class InsertTest {
@Test
public void testInsert(){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
//设置不允许自动提交数据
connection.setAutoCommit(false);
String sql="insert into test set name=?";
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < 100000; i++) {
preparedStatement.setObject(1,"name_"+i);
//1、攒SQL
preparedStatement.addBatch();
if (i%500==0){
//2、执行攒下的SQL
preparedStatement.executeBatch();
//3、清空batch
preparedStatement.clearBatch();
}
}
//统一提交数据
connection.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(connection,preparedStatement);
}
}
}