@SpringBootTestclassExecuteSqlScriptApplicationTests {
@AutowiredprivateDataSource dataSource;
@Testvoid contextLoads() throwsSQLException, IOException {
Resource classPathResource= new ClassPathResource("init/student.sql");
ScriptUtils.executeSqlScript(dataSource.getConnection(), classPathResource);//分批处理SQL脚本
batchExecuteSql(classPathResource, 5);
}/*** SQL脚本分解执行
*@paramresource SQL脚本资源
*@parambatchNumber 每多少条SQL执行一次
*@throwsSQLException
*@throwsIOException*/
public void batchExecuteSql(Resource resource, int batchNumber) throwsSQLException, IOException {
Connection connection=dataSource.getConnection();
Statement statement=connection.createStatement();
BufferedReader bufferedReader= null;try{//获取字符缓冲流
bufferedReader = new BufferedReader(newInputStreamReader(resource.getInputStream()));intl;int i = 0;
StringBuilder sql= newStringBuilder();while ((l = bufferedReader.read()) != -1) {char read = (char) l;
sql.append(read);if (read == ';') { //一个完整的SQL语句
i ++;
statement.addBatch(sql.toString());if (i % batchNumber == 0) {
System.out.println("每" + batchNumber + "条语句批量执行开始......");
statement.executeBatch();
statement.clearBatch();
System.out.println("每" + batchNumber + "条语句批量执行结束......");
}//清除StringBuilder中的SQL语句
sql.delete(0, sql.length());
}
}if (i % batchNumber != 0) {
System.out.println("执行最后不足" + batchNumber + "条语句开始!!!");
statement.executeBatch();
statement.clearBatch();
System.out.println("执行最后不足" + batchNumber + "条语句结束!!!");
}
}finally{if (bufferedReader != null) {
bufferedReader.close();
}if (connection != null) {
connection.close();
}if (statement != null) {
statement.close();
}
}
}
}