java cmd 执行sql文件_java执行SQL脚本文件

@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();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值