@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();
}
}
}
}
本文介绍了一种使用Java批量执行SQL脚本的方法。通过Spring Boot框架加载SQL文件,并利用ScriptUtils执行SQL脚本。此外,还实现了一种按批次执行SQL语句的功能,可以有效地提高执行效率。
292

被折叠的 条评论
为什么被折叠?



