import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MySQLBackup {
public static void main(String[] args) throws Exception {
// 备份示例
dbBackUp("127.0.0.1", "root", "123456", "3306",
"mybatis,mybatis-plus", "D:\\backup\\");
// 还原示例(注释掉,按需使用)
// reduction("127.0.0.1", "3306", "root", "123456",
// "mybatis-plus", "2021-07-27_14-19-04/mybatis-plus.sql");
}
/**
* 数据库备份方法
* @param host 主机地址
* @param userName 用户名
* @param password 密码
* @param port 端口
* @param dbNames 数据库名(多个用逗号分隔)
* @param backupPath 备份路径
*/
public static void dbBackUp(String host, String userName, String password,
String port, String dbNames, String backupPath) {
String format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
File backupDir = new File(backupPath + format);
if (!backupDir.mkdir()) {
System.out.println("创建备份目录失败");
return;
}
String[] dbNameArray = dbNames.split(",");
for (String dbName : dbNameArray) {
String pathSql = backupPath + format + "\\" + dbName + ".sql";
String cmd = "cmd /c mysqldump" + " -h" + host + " -P" + port +
" -u" + userName + " -p" + password + " " + dbName + " > " + pathSql;
System.out.println("执行命令:" + cmd);
try {
Process process = Runtime.getRuntime().exec(cmd);
if (process.waitFor() == 0) {
System.out.println(dbName + " 数据库备份成功!");
} else {
System.out.println(dbName + " 数据库备份失败!");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 数据库还原方法
* @param host 主机地址
* @param port 端口
* @param userName 用户名
* @param password 密码
* @param databaseName 数据库名
* @param fileName 备份文件路径
*/
public static void reduction(String host, String port, String userName,
String password, String databaseName, String fileName) throws Exception {
File datafile = new File(fileName);
if (!datafile.exists()) {
System.out.println(fileName + " 文件不存在,请检查");
return;
}
String cmd = "cmd /c mysql -h" + host + " -P" + port + " -u" + userName +
" -p" + password + " " + databaseName + " < " + datafile;
System.out.println("还原命令:" + cmd);
Process exec = Runtime.getRuntime().exec(cmd);
if (exec.waitFor() == 0) {
System.out.println(databaseName + " 数据库还原成功,还原文件:" + datafile);
} else {
System.out.println("数据库还原失败");
}
}
}