操作系统:Linux 数据库:MySQL
注意:只可用于备份代码运行环境下的数据库,例如A服务器运行代码,访问B服务器数据库进行备份,则不可行。
代码如下:
package com.remoteservice.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
/**
* Created by jlm on 2019-12-03 14:07
*/
@RestController
@RequestMapping("/back")
public class TestController {
@RequestMapping("up")
public void backup(){
try {
if (exportDatabaseTool("服务器IP", "mysql登录账户", "登录密码!", "保存的路径", "保存文件(注意以.sql文件)", "数据库名称")) {
System.out.println("数据库成功备份!!!");
} else {
System.out.println("数据库备份失败!!!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
}
PrintWriter printWriter = null;
BufferedReader bufferedReader = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
//备份指定表
// Process process = Runtime.getRuntime().exec("mysqldump remoteservice -h" + hostIP + " -u" + userName + " -p" + password +" --set-charset=UTF8 " + "--tables t_area");
//备份整个库
Process process = Runtime.getRuntime().exec("mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);
//备份除xxx表以外
// Process process = Runtime.getRuntime().exec("mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + "--ignore-table=" + databaseName + ".t_area " + databaseName);
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
printWriter.println(line);
printWriter.flush();
}
if (process.waitFor() == 0) {//0 表示线程正常终止。
return true;
}
System.out.println("code" + process.waitFor());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
以上代码亲测可用,好用记得点赞哦~