首先添加mysql的bin到环境变量,这样可以简写部分命令,并且做到不依赖系统mysql的具体安装路径。
重启计算机可以让添加的环境变量在java代码中调用时生效。(cmd中生效但java中调用没有生效,这是我遇到的情况)
java调用mysql备份命令用到:1,隐形调用cmd;2,调用第三方可执行程序;
cmd参数的说明:(详细参考地址:http://blog.csdn.net/xys_777/article/details/6164206)
cmd /c dir 是执行完dir命令后关闭命令窗口。
cmd /k dir 是执行完dir命令后不关闭命令窗口。
cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。
cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭。
备份代码:
String path = request.getSession().getServletContext().getRealPath("/"); String bakfile = "SQLBAK\bak.sql"; String cmd = "mysqldump -u root -h 127.0.0.1 -p123456 -P 3307 --default-character-set=UTF8 --add-drop-database -B ipms2 -r " +path+bakfile; try { Process runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", cmd}); int processComplete = runtimeProcess.waitFor(); if (processComplete == 0) { System.out.println("DatabaseManager.restore: Restore Successfull"); result=true; } else { System.out.println("DatabaseManager.restore: Restore Failure!"); result=false; } } catch (Exception e1) { e1.printStackTrace(); }
恢复代码:
String path = request.getSession().getServletContext().getRealPath("/"); String bakfile = "SQLBAK\bak.sql"; String cmd = "mysql -u root -h 127.0.0.1 -p123456 -P 3307 --default-character-set=UTF8 < " +path+bakfile; System.out.println(cmd); boolean result=true; try { Process runtimeProcess = Runtime.getRuntime().exec( new String[] { "cmd.exe", "/c", cmd }); int processComplete = runtimeProcess.waitFor(); if (processComplete == 0) { System.out .println("DatabaseManager.restore: Restore Successfull"); result = true; } else { System.out.println("DatabaseManager.restore: Restore Failure!"); result = false; } } catch (Exception e1) { e1.printStackTrace(); }