1.代码部分
/**
* 备份数据库
*
* @return 结果
*/
public AjaxResult backupSQL() {
String fileName = "/" + databasename + "_" + new Date().getTime() + ".sql";
//如果没有文件,先创建文件
//Global.getDatabasePath()你要创建的文件路径
File file = new File (Global.getDatabasePath() + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//判断系统格式
String cmd = "";
//Global.isIsWin()判断系统格式,如何判断自行百度
if (Global.isIsWin()){
cmd = "cmd /c mysqldump -h " + host + " -P " + port + " -u" + username + " -p" + password + " " + databasename + " > " + Global.getDatabasePath() + fileName; //-u后的root为mysql数据库用户名,-p后接的123456为该用户密码,注意不要有空格;dbName填写需要备份数据的数据库名称,大于号后接生成文件路径
}else {
cmd = "mysqldump -h " + host + " -P " + port + " -u" + username + " -p" + password + " " + databasename + " > " + Global.getDatabasePath() + fileName; //-u后的root为mysql数据库用户名,-p后接的123456为该用户密码,注意不要有空格;dbName填写需要备份数据的数据库名称,大于号后接生成文件路径
}
return backupSQLCommand(cmd,fileName);
}
/**
* 备份数据库
*
* @return 结果
*/
public AjaxResult backupSQLCommand(String cmd,String fileName){
Process process = null;
try {
if (Global.isIsWin()){
process = Runtime.getRuntime().exec(cmd);
}else {
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",cmd});
}
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
process.waitFor();
is.close();
//保存数据库信息到数据库
bimsDatasourceBackupMapper.insertBimsDatasourceBackup(new BimsDatasourceBackup() {{
setCreateTime(DateUtils.getNowDate());
setCreateId(ShiroUtils.getUserId());
setName(databasename);
setStoragePosition(getPathFileName(Global.getDatabasePath(),fileName));
setAddress(Global.getDatabasePath() + fileName);
setIsSystem(1);
}});
return AjaxResult.success("备份成功!");
} catch (Exception e) {
return AjaxResult.error("备份失败:"+e.getMessage());
}
}
/**
* 获取路径,以下方法仅仅适用于若依框架
*
* @return 结果
*/
private static final String getPathFileName(String uploadDir, String fileName) throws IOException
{
int dirLastIndex = Global.getProfile().length() + 1;
String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + fileName;
return pathFileName;
}
2.配置部分,
(1)运行这个项目的主机必须配有mysql和mysql的环境变量,因为使用的是mysql的dump
(2)将mysql安装路径下面的bin文件夹中的dump程序拷贝到项目jar所在地