/**
* 数据备份
* savePath 是路径
* type 是类型
*/
@RequestMapping("/dataBackUp")
@ResponseBody
public void dataBackUp(String savePath, int type) throws IOException {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
}
if (dataBackUps(savePath, type)) {
System.out.println("数据库备份成功!!!");
} else {
System.out.println("数据库备份失败!!!");
}
}
private static boolean dataBackUps(String savePath, int type) throws IOException {
StringBuilder command = new StringBuilder();
Runtime rt = Runtime.getRuntime();
Process pro = null;
command.append("mysqldump --opt -h 192.168.3.27 -u" + username + " -p" + password + " test ");
String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
String fileName =savePath +"/" + time + ".sql";
command.append("agricultural");
command.append(" ");
command.append("-w \" typeNumber="+type);
command.append("\"");
command.append(" ");
command.append("--result-file=" + fileName+" --default-character-set=utf8");
pro = rt.exec(command.toString());
//命令执行出错则打印相关错误信息
BufferedReader br = new BufferedReader(new InputStreamReader( pro.getErrorStream()));
String errorLine = null;
while ((errorLine = br.readLine()) != null) {
System.out.println(errorLine);
}
br.close();
return true;
}
在上面中192.168.3.27是mysql所在的ip地址,username 和password是链接数据库的用户名和密码,test 是数据库名,agricultural是表名,"-w " typeNumber="+type 表示在表中的type Number字段等于type的数据.