@RestController
@RequestMapping("/database")
@SuppressWarnings("all")
public class DatabaseController {
String host = "localhost";
String userName = "root";
String password = "root";
String database = "tingchechangzjnl";
String backupFolderPath = "D:/phpstudy_pro/database/";
String fileName = "tingchechangzjnl";
@RequestMapping(value = "/backup")
public R backup11() throws Exception {
//数据库备份
File backupFolderFile = new File(backupFolderPath);
if (!backupFolderFile.exists()) {
// 如果目录不存在则创建
backupFolderFile.mkdirs();
}
if (!backupFolderPath.endsWith(File.separator) && !backupFolderPath.endsWith("/")) {
backupFolderPath = backupFolderPath + File.separator;
}
// 拼接命令行的命令
String backupFilePath = backupFolderPath + fileName;
StringBuilder stringBuilder = new StringBuilder();
//此处需要到mysqldump的位置,有的存的地方可能会不同
stringBuilder.append("D:\\phpstudy_pro\\Extensions\\MySQL5.7.26\\bin\\mysqldump");
stringBuilder.append(" -h ").append(host).append(" -u").append(userName).append(" -p").append(password);
stringBuilder.append(" --result-file=").append(backupFilePath).append(".sql").append(" --default-character-set=utf8 ").append(database);
System.out.println(stringBuilder.toString());
// 调用外部执行 exe 文件的 Java API
Process process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));
if (process.waitFor() == 0) {
// 0 表示线程正常终止
System.out.println("数据已经备份到 " + backupFilePath + " 文件中");
return R.ok("数据备份成功!");
}
return R.error("数据备份失败!");
}
@RequestMapping(value = "/restore")
public R restore11() throws Exception {
//数据库导入
File restoreFile = new File(backupFolderPath);
if (restoreFile.isDirectory()) {
for (File file : restoreFile.listFiles()) {
if (file.exists() && file.getPath().endsWith(".sql")) {
backupFolderPath = file.getAbsolutePath();
break;
}
}
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("D:\\phpstudy_pro\\Extensions\\MySQL5.7.26\\bin\\mysql.exe -h ").append(host).append(" -u").append(userName).append(" -p").append(password);
stringBuilder.append(" ").append(database).append(" < ").append(backupFolderPath);
try {
Process process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));
if (process.waitFor() == 0) {
System.out.println("数据已从 " + backupFolderPath + " 导入到数据库中");
}
} catch (IOException e) {
e.printStackTrace();
return R.error("数据恢复失败!");
}
return R.ok("数据恢复成功!");
}
private static String[] getCommand(String command) {
String os = System.getProperty("os.name");
String shell = "/bin/bash";
String c = "-c";
if(os.toLowerCase().startsWith("win")){
shell = "cmd";
c = "/c";
}
String[] cmd = { shell, c, command };
return cmd;
}
}