废话不会说,直接上代码
//数据库所在电脑IP,可以是本地,也可以远程
private static String hostIP = “127.0.0.1”;
//数据库用户名
private static String userName = “mysql”;
//数据库密码
private static String password = “mysql”;
//备份文件存储位置
private static String savePath = “C:/test/”;
//要备份的数据库名称
private static String database = “test”;
//备份数据库
public Boolean backups() {
File saveFile = new File(savePath);
// 如果目录不存在
if (!saveFile.exists()) {
// 创建文件夹
saveFile.mkdirs();
}
//文件名test+当前年月日时分秒
String fileName = "test" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".sql";
//拼接命令行的命令
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
stringBuilder.append(" --user=").append(userName).append(" --password=").append(password)
.append(" --lock-all-tables=true");
stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ")
.append(database);
try {
//调用外部执行exe文件的javaAPI
Process process = Runtime.getRuntime().exec(mysqlPath() + stringBuilder.toString());
// 0 表示线程正常终止。
if (process.waitFor() == 0) {
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
// 还原数据库 url 备份文件存储位置
public Boolean recover(String url) {
// 要执行的恢复命令
String st = "mysql -h"+hostIP+" -u"+userName+" -p"+password+" --default-character-set=utf8 "+database + " < " + url;
String[] cmd = { "cmd", "/c", st };
try {
// 执行恢复命令
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}