Java备份&还原MySQL数据库

时间:2023-01-01 17:07:40

MySQL在登陆的情况下可以用SOURCE D:\test.sql这种方式来还原数据库,但是没有对应备份的命令,真是醉了。


1. BackupUtil类

package com.building.util;

import java.util.Properties;
import priv.dunhanson.util.RuntimeUtil;

/*
* 数据库备份/还原工具类
*/
public class BackupUtil {

/**
* 导出SQL
* @param properties
*/
public static void ExptSQL(Properties properties){
RuntimeUtil.execte(getExptCmd(properties));
}

/**
* 导入SQL
* @param properties
*/
public static void ImptSQL(Properties properties){
RuntimeUtil.execte(getImptCmd(properties));
}

/**
* 获取导出命令
* @param properties
* @return
*/
public static String getExptCmd(Properties properties){
StringBuffer cmd = new StringBuffer();
cmd.append(getOSCmd()).append(" ");
cmd.append("mysqldump").append(" ");
cmd.append("-h").append(properties.getProperty("ip")).append(" ");
cmd.append("-u").append(properties.getProperty("user")).append(" ");
cmd.append("-p").append(properties.getProperty("password")).append(" ");
cmd.append("-P").append(properties.getProperty("port")).append(" ");
cmd.append(properties.getProperty("database")).append(" ").append(">").append(" ");
cmd.append(properties.getProperty("path")).append(properties.getProperty("filename"));
return cmd.toString();
}

/**
* 获取导入命令
* @param properties
* @return
*/
public static String getImptCmd(Properties properties){
StringBuffer cmd = new StringBuffer();
cmd.append(getOSCmd()).append(" ");
cmd.append("mysql").append(" ");
cmd.append("-h").append(properties.getProperty("ip")).append(" ");
cmd.append("-u").append(properties.getProperty("user")).append(" ");
cmd.append("-p").append(properties.getProperty("password")).append(" ");
cmd.append("-P").append(properties.getProperty("port")).append(" ");
cmd.append(properties.getProperty("database")).append(" ").append("<").append(" ");
cmd.append(properties.getProperty("path")).append(properties.getProperty("filename"));
return cmd.toString();
}

/**
* 获取当前系统命令
* @return
*/
public static String getOSCmd(){
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
return "cmd /c";
}else if(osName.contains("Linux")){
return "sh -c";
}
return "";
}

public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("ip", "127.0.0.1");
properties.setProperty("user", "root");
properties.setProperty("password", "123456");
properties.setProperty("port", "3306");
properties.setProperty("database", "test");
properties.setProperty("path", "D:\\");
properties.setProperty("filename", "test.sql");
System.out.println(getExptCmd(properties));
}


}

2. RuntimeUtil类

package priv.dunhanson.util;

public class RuntimeUtil {

/**
* 执行命令
* @param execStr
*/
public static void execte(String execStr){
try {
Runtime.getRuntime().exec(execStr);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}