java代码
package com.acer.contrller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @RequestMapping(value = "/executeBatFile") @Api(value = "执行BAT文件") public class ExecuteBatFile { @RequestMapping(value = "/execute", method = RequestMethod.POST) @ApiOperation(value = "实现执行bat文件", response = String.class) public void execute(@ApiParam(value = "bat文件路径", required = true) @RequestParam("filePath") String filePath) { //更改路径 /** * 比如从前端传过来的bat存放路径为c:\bat\test.bat * 此时就要替换成c:\\bat\\test.bat * 因为\在java中是转义字符 */ String execFile = filePath.replace("\\", "\\\\"); String cmdStart = "cmd /c start " + execFile; Process process = null; Runtime runtime = Runtime.getRuntime(); try { //执行cmd窗口并执行bat文件 process = runtime.exec(cmdStart); } catch (Exception e) { // TODO: handle exception } try { process.waitFor(); } catch (Exception e) { // TODO: handle exception } int i = process.exitValue(); if (i == 0) { System.out.println("执行成功"); } else { System.out.println("执行失败"); } process.destroy(); } } |
bat文件
@echo off echo 准备链接数据库 C: cd C:\Program Files\MySQL\MySQL Server 5.7\bin echo 进去bin目录 REM bankdemo是数据库名,root,root是用户名和密码 mysql -uroot -proot bankdemo < C:\Users\acer\Desktop\mysql.sqlecho 链接数据库完成 exit |
mysql.sql文件
UPDATE county SET county_name='长丰县' WHERE county_id='1'; COMMIT; exit |